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

前端 未结 5 749
广开言路
广开言路 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:08

    This is my take on a recursive solution, which works for arrays of any depth:

    function convertArray($arr, $narr = array(), $nkey = '') {
        foreach ($arr as $key => $value) {
            if (is_array($value)) {
                $narr = array_merge($narr, convertArray($value, $narr, $nkey . $key . '.'));
            } else {
                $narr[$nkey . $key] = $value;
            }
        }
    
        return $narr;
    }
    

    Which can be called as $newArray = convertArray($myArray).

提交回复
热议问题