PHP: Turning multidimensional arrays to single dimension arrays

前端 未结 7 608
遇见更好的自我
遇见更好的自我 2021-01-02 10:53

Basically my app is interacting with a web service that sends back a weird multidimensional array such as:

Array
(
    [0] => Array
        (
                     


        
相关标签:
7条回答
  • 2021-01-02 11:10

    I am using laravel's helper: http://laravel.com/api/source-function-array_flatten.html#179-192

    function array_flatten($array)
        {
            $return = array();
    
            array_walk_recursive($array, function($x) use (&$return) { $return[] = $x; });
    
            return $return;
        }
    
    0 讨论(0)
  • 2021-01-02 11:18

    Consider $mArray as multidimensional array and $sArray as single dimensional array this code will ignore the parent array

    function flatten_array($mArray) {
        $sArray = array();
    
        foreach ($mArray as $row) {
            if ( !(is_array($row)) ) {
                if($sArray[] = $row){
                }
            } else {
                $sArray = array_merge($sArray,flatten_array($row));
            }
        }
        return $sArray;
    }
    
    0 讨论(0)
  • 2021-01-02 11:32
    $result = call_user_func_array('array_merge', $array);
    
    0 讨论(0)
  • 2021-01-02 11:33

    Like this:

    $result = array();
    
    foreach($array as $inner) {
        $result[key($inner)] = current($inner);        
    }
    

    The $result array would now look like this:

    Array
    (
        [Price] => 1
        [Size] => 7
        [Type] => 2
    )
    
    0 讨论(0)
  • 2021-01-02 11:33
    function flattenArray($input, $maxdepth = NULL, $depth = 0)
    {
        if(!is_array($input)){ 
          return $input;
        }
    
        $depth++;
        $array = array(); 
        foreach($input as $key=>$value){
          if(($depth <= $maxdepth or is_null($maxdepth)) && is_array($value)){
            $array = array_merge($array, flattenArray($value, $maxdepth, $depth));
          } else {
            array_push($array, $value);
            // or $array[$key] = $value;
          }
        }
        return $array;
    }
    
    0 讨论(0)
  • 2021-01-02 11:35

    I think i found best solution to this :

    array_walk_recursive($yourOLDmultidimarray, function ($item, $key) {
        //echo "$key holds $item\n";
    $yourNEWarray[]=$item;
    });
    

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