Location: PHPKode > scripts > Filter Array into Categorized format > filter-array-into-categorized-format/array2arraytree.php
<?php
/**
 * Array2ArrayTree
 * @package   
 * @author Gaurav Jassal
 * @copyright http://www.gauravjassal.com
 * @version 1.0
 * @access public
 */
class Array2ArrayTree
{
    public $arrOriginal = array();
    public $arrDummy = array();
    public $strKey = "";
    /**
     * Array2ArrayTree::__construct()
     * 
     * @param $arrData Array
     * @param $arrKey String 
     * @return
     */
    public function __construct($arrData, $arrKey)
    {
        $this->arrOriginal = $arrData;
        $this->strKey = $arrKey;
        $this->arrDummy = array();
    }

    /**
     * Array2ArrayTree::makeTree()
     * 
     * @return Array
     */
    public function makeTree()
    {
        for ($i = 0; $i <= sizeof($this->arrOriginal) - 1; $i++) {
            $keyPosition = $this->searchKey($this->arrOriginal[$i][$this->strKey]);
            if ($keyPosition == -1) {
                $this->addNode($this->arrOriginal[$i]);
            } else {
                $this->appendNode($this->arrOriginal[$i], $keyPosition);
            }
        }
        return $this->arrDummy;
    }
    /**
     * Array2ArrayTree::searchKey()
     * 
     * @param $strCurrentValue String
     * @return
     */
    function searchKey($strCurrentValue)
    {
        for ($i = 0; $i <= sizeof($this->arrDummy) - 1; $i++) {
            if ($this->arrDummy[$i][0][$this->strKey] == $strCurrentValue) {
                return $i;
            }
        }
        return - 1;
    }
    /**
     * Array2ArrayTree::addNode()
     * 
     * @param $arrNode Array
     * @return
     */
    function addNode($arrNode)
    {
        $this->arrDummy[sizeof($this->arrDummy)][0] = $arrNode;
    }
    /**
     * Array2ArrayTree::appendNode()
     * 
     * @param $arrNode Array
     * @param $keyPosition Integer
     * @return
     */
    function appendNode($arrNode, $keyPosition)
    {
        array_push($this->arrDummy[$keyPosition], $arrNode);
    }
}
?>

Return current item: Filter Array into Categorized format