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

前端 未结 5 719
广开言路
广开言路 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 15:58

    This will handle an arbitrary level of nesting:

     $value){
            if (\is_array($value) === true){
                foreach($dotFlatten($value, "$context$key.") as $iKey => $iValue){
                    $retval[$iKey] = $iValue;
                }
            } else {
                $retval["$context$key"] = $value;
            }
        }
        return $retval;
    };
    
    var_dump(
        $dotFlatten(
            [
                'key1' => 'value1',
                'key2' => [
                    'subkey' => 'subkeyval',
                ],
                'key3' => 'value3',
                'key4' => [
                    'subkey4' => [
                        'subsubkey4' => 'subsubkeyval4',
                        'subsubkey5' => 'subsubkeyval5',
                    ],
                    'subkey5' => 'subkeyval5',
                ],
            ]
        )
    );
    ?>
    

提交回复
热议问题