我試圖在多維數組中獲取搜索元素的密鑰數組。例如,我最初的數組是:PHP:通過多維數組並獲取搜索元素的密鑰數組
$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;
如果我試着去理解 '分離' 利用這個功能鍵鍵的排列:
$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'
]
沒事!
但是,當我嘗試獲取'Juicemaker'或'Iron'或'Product'鍵的數組時。它不工作,因爲我不能老是元素之後叫我getArrayOfkeys()函數:
$f['Kitchen']['Dishes']['Separator']=10;
- 我怎樣才能上述元素之後再打來?
我想獲取'Juicemaker'鑰匙['Kitchen', 'Blue things One', 'Juicemaker']
。
對於'產品'鍵['Kitchen','Product']
。
對於 '鐵' 鍵['Kitchen', 'Blue things','Iron']
- 我的功能似乎對我很未優化,幫助我,請與優化。
它會更好,如果你已經顯示了初始數組和預期的輸出 – RomanPerekhrest
可能重複的[如何從給定的子鍵查找數組的所有父鍵?](http://stackoverflow.com/questions/ 4814094 /如何找到一個給定的孩子的關鍵字的數組) – Mike
@Mike它不是 – juma