我试图在多维数组中获得搜索元素的键的数组。例如,我的初始数组是:
$f['Kitchen']['Dishes']['Mantovarka']=3;
$f['Kitchen']['Dishes']['Castrool']=91;
$f['Kitchen']['Dishes']['Separator']=10;
$f['Kitchen']['Product']=18;
$f['Kitchen']['Textile']=19;
$f['Kitchen']['Blue things One']['Juicemaker']=25;
$f['Kitchen']['Blue things One']['Freegener']=13;
$f['Kitchen']['Blue things']['Microwave']=4;
$f['Kitchen']['Blue things']['Iron']=24;
如果我尝试用这个函数获得'Separator'键的键数组:
$index=0; $array =[];
function getArrayOfkeys($needle, $haystack,$original,$array,$index) {
$index++;
$exists = false;
if(is_array($haystack)){
foreach ($haystack as $key => $val) {
$array[$index]=$key;
if($key == $needle){
$exists = true;
break;
}elseif(is_array($val)){
return getArrayOfkeys($needle, $val,$original,$array,$index);
}
}
}else{
$index--;
}
if($exists==true){
return $array;
}
else{
// I need here logic!!!
}
}
它返回我:
[
1 => 'Kitchen'
2 => 'Dishes'
3 => 'Separator'
]
it is fine!
但是当我试图获得'榨汁机'或'铁'或'产品'的键数组时。它不工作,因为我不能在元素后调用我的getArrayOfkeys()函数:
$f['Kitchen']['Dishes']['Separator']=10;
- 如何在上述元素之后再次调用?
我想获得"榨汁机"钥匙['Kitchen', 'Blue things One', 'Juicemaker']
。
对于'Product'键['Kitchen','Product']
。
For 'Iron' key ['Kitchen', 'Blue things','Iron']
- 我的功能对我来说似乎非常未优化,请帮助我,优化它。
请尝试此功能:
function findKeyPath($arr, $key, $path = '') {
foreach($arr as $k => $value) {
if(is_array($arr[$k])) {
$ret = findKeyPath($arr[$k], $key, $path.$k.',');
if(is_array($ret)) {
return $ret;
}
}else if($k == $key) {
return explode(',', $path.$key);
}
}
return null;
}
print_r(findKeyPath($f, 'Juicemaker'));
//Output: Array ( [0] => Kitchen [1] => Blue things One2 [2] => Juicemaker )
演示:https://3v4l.org/YJD7q