I have an object from a sql-query. Every entry has the keys (id, type, title, parent_id).
My example data:
Content of the sql-object $list (var_export()):
$array = array(0 => (object) array( 'id' => 1, 'type' => 'label', 'title' => 'Product Categories', 'parent_id' => 0, ),
1 => (object) array( 'id' => 2, 'type' => 'label', 'title' => 'Shoes', 'parent_id' => 1, ),
2 => (object) array( 'id' => 3, 'type' => 'label', 'title' => 'T-Shirts', 'parent_id' => 1, ),
3 => (object) array( 'id' => 4, 'type' => 'label', 'title' => 'With Print', 'parent_id' => 2, ),
4 => (object) array( 'id' => 5, 'type' => 'label', 'title' => 'Without Print', 'parent_id' => 2, ),
5 => (object) array( 'id' => 6, 'type' => 'label', 'title' => 'Brands', 'parent_id' => 2, ),
6 => (object) array( 'id' => 7, 'type' => 'label', 'title' => 'Blue', 'parent_id' => 3, ),
7 => (object) array( 'id' => 8, 'type' => 'label', 'title' => 'Red', 'parent_id' => 3, ));
What i expect:
the function, should find the dependencies of the entries starting with a given id. Here for example the ID 7:
Array
(
[0] => stdClass Object
(
[id] => 7
[type] => "label"
[title] => "Blue"
[parent_id] => 3
)
[1] => stdClass Object
(
[id] => 3
[type] => "label"
[title] => "T-Shirts"
[parent_id] => 1
)
[2] => stdClass Object
(
[id] => 1
[type] => "label"
[title] => "Product Categories"
[parent_id] => 0
)
)
What i get:
I just get an array with the first entry, with the id I started with. As example with starting ID 7:
array ( 0 => (object) array( 'id' => 7, 'type' => 'label', 'title' => 'Blue', 'parent_id' => 3, ), )
My current Function:
The function needs to search for the item with the given id, stores the information into a new array and then start a new search but with the parent_id as new search id. This should loop as long as there are dependencies, if there are no dependencies the loop should stop and returning the created array.
function getParentSelect($list, $parent) {
$next_id = true;
$result = array();
foreach($list as $k => $s) {
echo $s->id;
if ($s->id == $parent) {
$result[] = $s;
$next_id = $s->parent_id;
break;
}
else {
$next_id = false;
}
}
if ($next_id != false) {
$result = array_merge($result, getParentSelect($list, $next_id));
}
return $result;
}