【问题标题】:How can I create an associative array from a foreach loop?如何从 foreach 循环创建关联数组?
【发布时间】:2016-09-09 20:59:48
【问题描述】:
$array = ["farm"=>
              [
                "horse"=>
                 [
                  "rabbit"=>
                     [
                      "fred1"=> "fred1",
                      "fred2"=> "fred2",
                      "fred3"=> "fred3",
                      "fred4"=> "fred4"
                    ],
                 "raccoon"=>
                    ["frida"=> "frida"]
                  ]  
              ]
    ]; 

我想为每个循环创建一个数组:

$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, '');

我的结果是:

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

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

)

我真正期望的是:

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

    )

https://eval.in/571065

【问题讨论】:

  • 你的预期输出有什么区别?
  • @splash58 我的输出是两个数组,但我只需要一个数组
  • 什么是 $keySearch ?
  • 这里是$keySearch = "o"
  • 为什么 john 不在结果中?

标签: php arrays multidimensional-array associative-array


【解决方案1】:

递归算法解决方案:

    <?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"));

【讨论】:

    【解决方案2】:

    我改进了你的代码:

     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:如果您找到所有键,而不仅仅是那些指向数组的键,请更改代码:

    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

    【讨论】:

    • 例如,如果数组中有key=>value,则不会被第1个代码选中,会被第2个,。但是 $key=>[array] 在这两种情况下都会出现
    【解决方案3】:

    您可以将相同的函数与添加 ref 属性一起使用,并将数组附加到该属性中。

    $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);
    

    演示:https://eval.in/571224

    【讨论】:

      【解决方案4】:

      当然,这就是您寻求的解决方案:

      <?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"));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-20
        • 2020-05-01
        • 1970-01-01
        • 2012-04-26
        • 2013-01-12
        • 1970-01-01
        相关资源
        最近更新 更多