How to “flatten” a multi-dimensional array to simple one in PHP?

前端 未结 23 2544
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 01:03

It\'s probably beginner question but I\'m going through documentation for longer time already and I can\'t find any solution. I thought I could use implode for each dimensio

23条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 01:14

    Someone might find this useful, I had a problem flattening array at some dimension, I would call it last dimension so for example, if I have array like:

    array (
      'germany' => 
      array (
        'cars' => 
        array (
          'bmw' => 
          array (
            0 => 'm4',
            1 => 'x3',
            2 => 'x8',
          ),
        ),
      ),
      'france' => 
      array (
        'cars' => 
        array (
          'peugeot' => 
          array (
            0 => '206',
            1 => '3008',
            2 => '5008',
          ),
        ),
      ),
    )
    

    Or:

    array (
      'earth' => 
      array (
        'germany' => 
        array (
          'cars' => 
          array (
            'bmw' => 
            array (
              0 => 'm4',
              1 => 'x3',
              2 => 'x8',
            ),
          ),
        ),
      ),
      'mars' => 
      array (
        'france' => 
        array (
          'cars' => 
          array (
            'peugeot' => 
            array (
              0 => '206',
              1 => '3008',
              2 => '5008',
            ),
          ),
        ),
      ),
    )
    

    For both of these arrays when I call method below I get result:

    array (
      0 => 
      array (
        0 => 'm4',
        1 => 'x3',
        2 => 'x8',
      ),
      1 => 
      array (
        0 => '206',
        1 => '3008',
        2 => '5008',
      ),
    )
    

    So I am flattening to last array dimension which should stay the same, method below could be refactored to actually stop at any kind of level:

    function flattenAggregatedArray($aggregatedArray) {
        $final = $lvls = [];
        $counter = 1;
        $lvls[$counter] = $aggregatedArray;
    
    
        $elem = current($aggregatedArray);
    
        while ($elem){
            while(is_array($elem)){
                $counter++;
                $lvls[$counter] = $elem;
                $elem =  current($elem);
            }
    
            $final[] = $lvls[$counter];
            $elem = next($lvls[--$counter]);
            while ( $elem  == null){
                if (isset($lvls[$counter-1])){
                    $elem = next($lvls[--$counter]);
                }
                else{
                    return $final;
                }
            }
        }
    }
    

提交回复
热议问题