3v4l.org

run code in 300+ PHP versions simultaneously
<?php $tree = [ [ "id" => 1573695284631, "name" => "Cars", "pid" => 0, "children" => [ [ "id" => 1573695292010, "name" => "Audi", "pid" => 1573695284631 ], [ "id" => 1573695305619, "name" => "BMW", "pid" => 1573695284631, "children" => [ [ "id" => 1573695328137, "name" => "3 Series", "pid" => 1573695305619 ], [ "id" => 1573695335102, "name" => "X5", "pid" => 1573695305619 ] ] ] ] ], [ "id" => 1573695348647, "name" => "Motorcycles", "pid" => 0, "children" => [ [ "id" => 1573695355619, "name" => "Ducatti", "pid" => 1573695348647 ] ] ] ]; var_dump(getParentNodes($tree, 1573695335102)); function getParentNodes($haystack, $child_node_id) { foreach ($haystack as $element) { if ($element['id'] === $child_node_id) { // return [$element['id']]; // uncomment if you want to include child itself return []; } else if (array_key_exists('children', $element)) { $parentNodes = getParentNodes($element['children'], $child_node_id); if ($parentNodes !== false) { return [$element['id'], ...$parentNodes]; } } } return false; }

preferences:
152.6 ms | 404 KiB | 5 Q