Convert multidimensional array into single array

后端 未结 20 1908
时光取名叫无心
时光取名叫无心 2020-11-22 10:39

I have an array which is multidimensional for no reason

/* This is how my array is currently */
Array
(
[0] => Array
    (
        [0] => Array
                


        
20条回答
  •  感动是毒
    2020-11-22 11:23

    Your sample array has 3 levels. Because the first level has only [0], you can hardcode your access into it and avoid an extra function/construct call.

    (Code Demos)

    1. array_walk_recursive() is handy and versatile, but for this task may be overkill and certainly a bit more convoluted in terms of readability.

      array_walk_recursive($array, function($leafvalue)use(&$flat){$flat[] = $leafvalue;});
      var_export($flat);
      
    2. If this was my code, I'd be using array_column() because it is direct and speaks literally about the action being performed.

      var_export(array_column($array[0], 'plan'));
      
    3. Of course a couple of `foreach() loops will perform very efficiently because language constructs generally perform more efficiently than function calls.

      foreach ($array[0] as $plans) {
          foreach ($plans as $value) {
              $flat[] = $value;
          }
      }
      var_export($flat);
      
    4. Finally, as a funky alternative (which I can't imagine actually putting to use unless I was writing code for someone whom I didn't care for) I'll offer an array_merge_recursive() call with a splat operator (...).

      var_export(array_merge_recursive(...$array[0])['plan']);
      

提交回复
热议问题