3v4l.org

run code in 300+ PHP versions simultaneously
<?php function custom($arr, $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($arr)) { return $arr; } $result = []; // empty array to hold copy of subject foreach ($arr 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 $result[$key] = custom($value, $newKey, $oldKey); } return $result; } $var = '[{"player":"Tiger Woods"},{"player":"Gary Player"}]'; $temp = json_decode($var, true); $temp = custom($temp, 'golfer','player'); print_r($temp);
Output for 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.34, 8.2.0 - 8.2.30, 8.3.0 - 8.3.30, 8.4.1 - 8.4.18, 8.5.0 - 8.5.3
Array ( [0] => Array ( [golfer] => Tiger Woods ) [1] => Array ( [golfer] => Gary Player ) )

preferences:
90.89 ms | 1633 KiB | 4 Q