Convert multidimensional array into single array

后端 未结 20 1561
时光取名叫无心
时光取名叫无心 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:04
     $singleArray = array();
    
        foreach ($multiDimensionalArray as $key => $value){
            $singleArray[$key] = $value['plan'];
        }
    

    this is best way to create a array from multiDimensionalArray array.

    thanks

    0 讨论(0)
  • 2020-11-22 11:04

    Despite that array_column will work nice here, in case you need to flatten any array no matter of it's internal structure you can use this array library to achieve it without ease:

    $flattened = Arr::flatten($array);
    

    which will produce exactly the array you want.

    0 讨论(0)
  • 2020-11-22 11:05

    Just assign it to it's own first element:

    $array = $array[0];
    
    0 讨论(0)
  • 2020-11-22 11:06

    Assuming this array may or may not be redundantly nested and you're unsure of how deep it goes, this should flatten it for you:

    function array_flatten($array) { 
      if (!is_array($array)) { 
        return FALSE; 
      } 
      $result = array(); 
      foreach ($array as $key => $value) { 
        if (is_array($value)) { 
          $result = array_merge($result, array_flatten($value)); 
        } 
        else { 
          $result[$key] = $value; 
        } 
      } 
      return $result; 
    } 
    
    0 讨论(0)
  • 2020-11-22 11:07

    This simple code you can use

    $array = array_column($array, 'value', 'key');
    
    0 讨论(0)
  • 2020-11-22 11:10

    For this particular case, this'll do:

    $array = array_map('current', $array[0]);
    

    It's basically the exact same question is this one, look at some answers there: PHP array merge from unknown number of parameters.

    0 讨论(0)
提交回复
热议问题