开发者

Add a new dimension to a multidimensional array without having the full path

开发者 https://www.devze.com 2023-01-09 19:08 出处:网络
Apologies if my title is confusing. I have a table of categories that looks something like this: ID, Name,Parent

Apologies if my title is confusing. I have a table of categories that looks something like this:

ID, Name,    Parent
1, Cat1,     0
2, Cat1_1,   1
3, Cat1_2,   1
4, Cat2,     0
5, Cat2_1,   4
6, Cat2_1_1, 5

I am trying to get this into a multidimensional array so that the category tree is available in its correct format for display purposes etc.

I am writing a recursive function (inside a class), that writes each level of the category tree to a class variable. My problem is that once I get down past the second level, I loose the ability to reference the class var in order to create the current categories children.

I can get a string representation of the array path, but is there a way that I can then evaluate that to give me access to the correct level of the array...

by example:

$path_string = "[4]['children'][5]['children']";

Is there some function that would allow me to then say $cat_path = $cats.$path_string so that $cat_path is pointing to the correct level of the array.

Sorry if this al开发者_开发问答l sounds a bit confusing. Alternatively, if anyone knows of a better way to get the data (as in the table example above) into a correct multidimensional array, please let me know!

Thanks


You can create a function which can descend the path for you. For example:

function descend($array, $path) {
    foreach ($path as $pathMember) {
        if (!array_key_exists($array, $pathMember)) {
            return null;
        }

        $array = $array[$pathMember];

        if (!array_key_exists($array, 'children')) {
            // or throw
            return null;
        }

        $array = $array['children'];
    }

    return $array;
}

$descended = descend($categories, array(4, 5));


Assuming a flat array with (id, name, parent):

$treearray = array(0 => array('children'=>array()));
foreach($flatarray as $item){
    if(!isset($treearray[$item['id']])){
        $treearray[$item['id']] = array();
    }
    $treearray[$item['id']] = array_merge($item,$treearray[$item['id']]);
    if(!isset($treearray[$item['parent']]){
        $treearray[$item['parent']] = array('children'=>array());
    }
    $treearray[$item['parent']]['children'][$item['id']] = &$treearray[$item['id']];
}
print_r($treearray[0]);

Optionally, you could also create a reference to it's parent in an item, creating the possiblity to go either way using $treearray[$the_id_youre_interested_in] Don't try to var_dump / print_r it anymore at that moment though, recursionfest deluxe.


Try using pure function.

Your function should accept a parent ID and return an array of its children, WITHOUT CHANGING ANY STATE OF ANY OBJECT.

That would be much less confusing.

0

精彩评论

暂无评论...
验证码 换一张
取 消