How do I create an associative array from a foreach loop?

advertisements
$array = ["farm"=>
              [
                "horse"=>
                 [
                  "rabbit"=>
                     [
                      "fred1"=> "fred1",
                      "fred2"=> "fred2",
                      "fred3"=> "fred3",
                      "fred4"=> "fred4"
                    ],
                 "raccoon"=>
                    ["frida"=> "frida"]
                  ]
              ]
    ];

I want to create an array from my for each loop:

$keySearch = "o";

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

My result is:

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

)
Array
(
    [0] => Array
        (
            [key] => raccoon
            [basePath] => farm/horse/raccoon
        )

)

What I actually expect is:

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

    )

https://eval.in/571065


i improved your code:

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

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

demo

UPD: if you find all keys, not only those which points array, change code so:

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 = 'fr';
$res = createList($array, $keySearch);
print_r($res);

demo