I have a multidimensional array:
$array = ["farm"=>
[
"horse"=>
[
"horseman"=>
[
"fred1"=> "fred1",
"fred2"=> "fred2",
"fred3"=>"fred3",
"fred4"=> "fred4"
],
"horseman2"=>
["john"=> "john"]
]
]
];
And I am searching in this array for a specific key:
function findKey($array, $keySearch) {
foreach ($array as $key => $item) {
$basePath = $basePath === null ? $key : $basePath. "/" . $key;
if (stripos($key, $keySearch) !== false){
echo "<li>Path:".$basePath."</li>";
echo "<li>".$key."</li>";
}
if (is_array($item))
findKey($item, $keySearch);
}
}
findKey($array, 'horse');
What I need is simply the "paths" of my resulted keys.
But my result is:
I tried so many ways, but I cannot achieve what I need :(
Here some examples:
findKey($array, 'horse');
findKey($array, 'horseman');
findKey($array, 'horseman2');
Try this function
Check the Script online Script.
Because you call the same function again and again, so you lost the value of
basepath
. So pass this every time you call the function.
function findKey($array, $keySearch, $basePath) {
$basePath2 = '';
foreach ($array as $key => $item) {
$basePath = ($basePath == "") ? $key : $basePath. "/" . $key;
if($key == $keySearch){
if(is_array($item)){
foreach($item as $key2 => $value){
$basePath2 = ($basePath2 == "") ? $key : $basePath2. "/" . $key;
echo "<li>Path:".$basePath."</li>";
echo "<li>".$key2."</li>";
}
}
break;
}else{
if(is_array($item)){
foreach($item as $key3 => $value3){
echo "<li>Path:".$basePath."</li>";
echo "<li>".$key3."</li>";
}
}
}
if(is_array($item))
findKey($item, $keySearch, $basePath);
}
}
findKey($array, 'horse', '');
Result
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments