Home > Backend Development > PHP Tutorial > 如何查找指定键的路径

如何查找指定键的路径

WBOY
Release: 2016-06-23 14:08:34
Original
1126 people have browsed it

想要在一个有特定规律的数组中查找一个键的路径 比如以下代码 要查找 红富士的键  返回一个包括它父级路径的数组  array(2, 3, 5, 9)

高手帮个忙  谢谢了   我研究一大天了  没有搞定  

	$array = array(		1=>array(			"name"=>"粮油"		),		2=>array(			"name"=>"果蔬",			"chlids"=>array(				3=>array(					"name"=>"水果",					"chlids"=>array(						5=>array(							"name"=>"苹果",							"childs"=>array(								8=>array(									"name"=>"青苹果",								),								9=>array(									"name"=>"红富士",								)							)						),						6=>array(							"name"=>"橘子"						),						7=>array(							"name"=>"大鸭梨"						)					)				),				4=>array(					"name"=>"蔬菜",					"chlids"=>array(						3=>array(							"name"=>"白菜"						),						3=>array(							"name"=>"芹菜"						)					)				),						)		)	);
Copy after login


回复讨论(解决方案)

$r = find($array, '红富士');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;}
Copy after login
Copy after login
Array
(
[0] => 2
[1] => 3
[2] => 5
[3] => 9
)

另外请注意:你的部分 childs 键名写错了,写成了 chlids

$r = find($array, '红富士');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;}
Copy after login
Copy after login
Array
(
    [0] => 2
    [1] => 3
    [2] => 5
    [3] => 9
)

另外请注意:你的部分 childs 键名写错了,写成了 chlids



还在吗?我的问题有点错误,是查找红富士的键 也就是9   然后返回这个结果  这个结果是对的

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template