How to find the path of a specified key

Source: Internet
Author: User
You want to find a path to a key in a specific array of rules such as the following code to find the Red Fuji key to return an array that includes its parent path array (2, 3, 5, 9)

Master, do me a favor. I've been working on it for a whole day.

$array = Array (1=>array ("name" = "oil"), 2=>array ("name" = "Fruit", "chlids" =>array ("name" = > "Fruit", "chlids" =>array (5=>array ("name" + "Apple", "Childs" =>array (8=>array ("name" = "Green apple",), 9 = >array ("Name" = "Red Fuji",)), 6=>array ("name" = "Orange"), 7=>array ("name" = "Big Pear")), 4=>array ("name" = "Vegetables", "chlids" =>array (3=>array ("name" = "cabbage"), 3=>array ("name" = "celery")));


Reply to discussion (solution)

$r = Find ($array, ' Red Fuji ');p Rint_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
)

Also please note: Your part of the childs key name is wrong, written in Chlids

$r = Find ($array, ' Red Fuji ');p Rint_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
)

Also please note: Your part of the childs key name is wrong, written in Chlids



Are you still there? My problem is a bit wrong, is to find the Red Fuji key is 9 and then return this result is correct
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.