Jarla Jarla - 6 months ago 18
PHP Question

How can I find only keys from a multidimensional array that have a key as a child?

My code is finding all keys with a specific character from my multidimensional array:

<?
$array = ["farm"=>
[
"horse"=>
[
"rabbit"=>
[
"name"=> "alan",
"age"=> "21",
"size"=> "166",
"gender"=> "f"
],
]
]
];

function createList($array, $keySearch, $path=null) {
$result = [];
foreach ($array as $key => $item) {
$basePath = $path === null ? $key : $path. "/" . $key;
if (stripos($key, $keySearch) !== false)
$result[] = ['key' => $key, 'basePath' => $basePath];
if(is_array($item))
$result = array_merge($result, createList($item, $keySearch, $basePath));
}
return $result;
}

$keySearch = 'a';
$res = createList($array, $keySearch);
print_r($res);


https://eval.in/573212

My output:

Array
(
[0] => Array
(
[key] => farm
[basePath] => farm
)

[1] => Array
(
[key] => rabbit
[basePath] => farm/horse/rabbit
)

[2] => Array
(
[key] => name
[basePath] => farm/horse/rabbit/name
)

[3] => Array
(
[key] => age
[basePath] => farm/horse/rabbit/age
)

)


But I need only the keys, that have a key as a child. So in this case my result should be:

Array
(
[0] => Array
(
[key] => farm
[basePath] => farm
)

[1] => Array
(
[key] => rabbit
[basePath] => farm/horse/rabbit
)
)

Answer

May be this is what you are looking for, please check and let me know. Just check your item has childs or not by using is_array($item) in the if condition.

online Check

Just change the function:

function createList($array, $keySearch, $path=null) {
    $result = [];
    foreach ($array as $key => $item) { 
        $basePath = $path === null ? $key : $path. "/" . $key;
        if (stripos($key, $keySearch) !== false && is_array($item)){
            $result[] = ['key' => $key, 'basePath' => $basePath];
        }       
        if(is_array($item))
            $result = array_merge($result, createList($item, $keySearch, $basePath));
    }
    return $result;
}
Comments