开发者

PHP returning all IDs from an array of parent/children given an id

开发者 https://www.devze.com 2023-03-26 07:16 出处:网络
Having a problem here that maybe someone can help me with. Hours of searching couldn\'t find the solution so I\'m at my wit\'s end.

Having a problem here that maybe someone can help me with. Hours of searching couldn't find the solution so I'm at my wit's end.

I have an array,

$array = array(
array('id' => 1, 'parent_id' =开发者_JAVA技巧> 0, 'name' => 'Main'),
array('id' => 2, 'parent_id' => 0, 'name' => 'Something'),
array('id' => 3, 'parent_id' => 1, 'name' => 'Child of Main'),
array('id' => 4, 'parent_id' => 3, 'name' => 'Child of Child of Main'),
...
);

I want a function that will give me all of the ids of the parents for a given node, i.e.

$ids = getIDs(4);

would return an array of {3, 1}

Any suggestions? Thank you in advance.


I've made something similar to RiaD (but on my own). It works well with the structure you already have.

<?php
$array = array(
array('id' => 1, 'parent_id' => 0, 'name' => 'Main'),
array('id' => 2, 'parent_id' => 0, 'name' => 'Something'),
array('id' => 3, 'parent_id' => 1, 'name' => 'Child of Main'),
array('id' => 4, 'parent_id' => 3, 'name' => 'Child of Child of Main'),
);
$parents = array();
function getIDs($id){
    global $array, $parents;
    $tmp = $array[$id-1]['parent_id'];
    if($tmp){
        array_push($parents, $tmp);
        getIDs($tmp);
    }
}
getIDs(4);
var_dump($parents);
?>


Is it possible to make structure like this?

 $array = array(
1=>array('id' => 1, 'parent_id' => 0, 'name' => 'Main'),
2=>array('id' => 2, 'parent_id' => 0, 'name' => 'Something'),
3=>array('id' => 3, 'parent_id' => 1, 'name' => 'Child of Main'),
4=>array('id' => 4, 'parent_id' => 3, 'name' => 'Child of Child of Main'),
...
);

with or without 'id' inside array

This one should works with this structure

function getIds($array,$x){
    if(!$array[$x]['parent_id'])
        return array();
    else
        return array_merge(array($array[$x]['parent_id']),getIds($array,$array[$x]['parent_id']));
}


you can try foreach loop or use array_count_values

0

精彩评论

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