PHP - Convert multidimensional array to 2D array with dot notation keys

前端 未结 5 748
广开言路
广开言路 2020-11-27 15:22

There are plenty of tips and code examples out there of accessing PHP arrays with dot notation, but I would like to do somewhat the opposite. I would like to take a multidim

5条回答
  •  没有蜡笔的小新
    2020-11-27 16:01

    There is already the answer with RecursiveIteratorIterator. But here is a more optimal solution, that avoids using nested loops:

    $iterator = new RecursiveIteratorIterator(
        new RecursiveArrayIterator($arr),
        RecursiveIteratorIterator::SELF_FIRST
    );
    $path = [];
    $flatArray = [];
    
    foreach ($iterator as $key => $value) {
        $path[$iterator->getDepth()] = $key;
    
        if (!is_array($value)) {
            $flatArray[
                implode('.', array_slice($path, 0, $iterator->getDepth() + 1))
            ] = $value;
        }
    }
    

    There are several points need to be made here. Notice the use of RecursiveIteratorIterator::SELF_FIRST constant here. It is important as the default one is RecursiveIteratorIterator::LEAVES_ONLY which wouldn't let us access all keys. So with this constant set, we start from the top level of an array and go deeper. This approach lets us store the history of keys and prepare the key when we rich leaf using RecursiveIteratorIterator::getDepth method.

    Here is a working demo.

提交回复
热议问题