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

前端 未结 23 2497
没有蜡笔的小新
没有蜡笔的小新 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:18

    Sorry for necrobumping, but none of the provided answers did what I intuitively understood as "flattening a multidimensional array". Namely this case:

    [
      'a' => [
        'b' => 'value',
      ]
    ]
    

    all of the provided solutions would flatten it into just ['value'], but that loses information about the key and the depth, plus if you have another 'b' key somewhere else, it will overwrite them.

    I wanted to get a result like this:

    [
      'a_b' => 'value',
    ]
    

    array_walk_recursive doesn't pass the information about the key it's currently recursing, so I did it with just plain recursion:

    function flatten($array, $prefix = '') {
        $return = [];
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $return = array_merge($return, flatten($value, $prefix . $key . '_'));
            } else {
                $return[$prefix . $key] = $value;
            }
        }
        return $return;
    }
    

    Modify the $prefix and '_' separator to your liking.

    Playground here: https://3v4l.org/0B8hf

提交回复
热议问题