How to replace key in multidimensional array and maintain order

前端 未结 1 1868
旧时难觅i
旧时难觅i 2021-01-07 05:45

Given this array:

$list = array(
   \'one\' => array(
       \'A\' => 1,
       \'B\' => 100,
       \'C\' => 1234,
   ),
   \'two\' => array(         


        
1条回答
  •  失恋的感觉
    2021-01-07 06:34

    This function should replace all instances of $oldKey with $newKey.

    function replaceKey($subject, $newKey, $oldKey) {
    
        // if the value is not an array, then you have reached the deepest 
        // point of the branch, so return the value
        if (!is_array($subject)) return $subject;
    
        $newArray = array(); // empty array to hold copy of subject
        foreach ($subject as $key => $value) {
    
            // replace the key with the new key only if it is the old key
            $key = ($key === $oldKey) ? $newKey : $key;
    
            // add the value with the recursive call
            $newArray[$key] = replaceKey($value, $newKey, $oldKey);
        }
        return $newArray;
    }
    

    0 讨论(0)
提交回复
热议问题