How can I find the path of a specified key? I want to find a key path in an array with a specific rule. for example, the following code is used to search for a red Fuji key and returns an array containing its parent path (2, 3, 5, 9)
Thanks for helping me out. I 've been studying it for a whole day.
$ Array = array (1 => array ("name" => "Grain and Oil"), 2 => array ("name" => "fruits and vegetables ", "chlids" => array (3 => array ("name" => "fruit ", "chlids" => array (5 => array ("name" => "apple ", "childs" => array (8 => array ("name" => "qingapple ",), 9 => array ("name" => "Red Fuji",), 6 => array ("name" => "orange "), 7 => array ("name" => ""), 4 => array ("name" => "vegetables ", "chlids" => array (3 => array ("name" => "cabbage "), 3 => array ("name" => "celery "))),)));
Reply to discussion (solution)
$ R = find ($ array, 'redfu'); print_r ($ r); function find ($ ar, $ name = '') {$ res = array (); foreach ($ ar as $ k =>$ v) {if ($ v ['name'] ==$ name) $ res [] = $ k; elseif (isset ($ v ['childs']) &! $ Res) {$ res = find ($ v ['childs'], $ name); if ($ res) array_unshift ($ res, $ k );}} return $ res ;}
Array
(
[0] => 2
[1] => 3
[2] => 5
[3] => 9
)
Note that some of your childs key names are incorrectly written as chlids
$ R = find ($ array, 'redfu'); print_r ($ r); function find ($ ar, $ name = '') {$ res = array (); foreach ($ ar as $ k =>$ v) {if ($ v ['name'] ==$ name) $ res [] = $ k; elseif (isset ($ v ['childs']) &! $ Res) {$ res = find ($ v ['childs'], $ name); if ($ res) array_unshift ($ res, $ k );}} return $ res ;}
Array
(
[0] => 2
[1] => 3
[2] => 5
[3] => 9
)
Note that some of your childs key names are incorrectly written as chlids
Are you still there? My problem is a bit wrong. it is correct to search for the Red Fuji key, that is, 9, and then return this result.