3
$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

9
  • what a diff between your an expected output? Commented May 13, 2016 at 15:26
  • @splash58 My output are two arrays, but I need only one array Commented May 13, 2016 at 15:27
  • what is $keySearch ? Commented May 13, 2016 at 15:35
  • in this case it is $keySearch = "o" Commented May 13, 2016 at 15:36
  • Why john is not in result? Commented May 13, 2016 at 15:38

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

for example, if there is key=>value in array, it will be not selected by 1st code and will be by 2nd,. But $key=>[array] will be in both cases
1

You can use your same function with addition ref attribute, and append array into that attribute.

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

function createList($array, $keySearch, $path, &$out) {
    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;
                $out[] = array_merge_recursive ($a, $b);            
            }
            createList($item, $keySearch, $basePath, $out);
        }       
    }
}

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

Demo: https://eval.in/571224

Comments

1

RECURSIVE ALGORITHM SOLUTION:

    <?php

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


            $jl     = array();
            $root   = "";

            function walkJarLarsData($ar, $search, $base="base-path", $pKey=""){
                global $jl, $root;
                if(!stristr($root, $base)){
                    $root  .= $base;
                }

                foreach($ar as $key=>$val){
                    $pKey       = $pKey?"{$pKey}":"";
                    if (preg_match("#" . preg_quote($search) . "#", $key)) {
                        $jl[]   = array(
                            "key"       => $key,
                            "basePath"  => $root . "/{$pKey}/{$key}",
                        );
                    }
                    if(is_array($val)){
                        walkJarLarsData($val, $search, $base, $key);      
                    }
                }


                return $jl;
            }

            var_dump(walkJarLarsData($array, "o"));

Comments

1

assuredly, this is the solution you seek:

<?php

    $arBase     = array();
    $kern       = "";

    function arrayRecurse($ar, $search, $mainPath="base-path", $cue=""){
        global $arBase, $kern;
        $kern   = !(stristr($kern, $mainPath))? $kern.= $mainPath : $kern;

        foreach($ar as $key=>$val){
            $cue       = $cue?"{$cue}":"";
            if (preg_match("#" . preg_quote($search) . "#", $key)) {
                $arBase[]   = array(
                    "key"       => $key,
                    "basePath"  => $kern . "/{$cue}/{$key}",
                );
            }
            if(is_array($val)){
                arrayRecurse($val, $search, $mainPath, $key);
            }
        }

        return $arBase;
    }

    var_dump(arrayRecurse($array, "fr"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.