Voting

: two plus five?
(Example: nine)

The Note You're Voting On

EllisGL
6 years ago
For those that think they can't use array_walk to change / replace a key name, here you go:

<?php
function array_explore(array &$array, callable $callback)
{
array_walk($array, function(&$value, $key) use (&$array, $callback)
{
$callback($array, $key, $value);

if(
is_array($value))
{
array_explore($value, $callback);
}
});
}

/**
* Stolen from: https://stackoverflow.com/questions/13233405/change-key-in-associative-array-in-php
*/
function renameKey(array &$data, $oldKey, $newKey, $ignoreMissing = false, $replaceExisting = false)
{
if (!empty(
$data))
{
if (!
array_key_exists($oldKey, $data))
{
if (
$ignoreMissing)
{
return
FALSE;
}

throw new
\Exception('Old key does not exist.');
}
else
{
if (
array_key_exists($newKey, $data))
{
if (
$replaceExisting)
{
unset(
$data[$newKey]);
}
else
{
throw new
\Exception('New key already exist.');
}
}

$keys = array_keys($data);

// Fix from EllisGL: http://php.net/manual/en/function.array-search.php#122377
$keys[array_search($oldKey, array_map('strval', $keys))] = $newKey;

$data = array_combine($keys, $data);

return
TRUE;
}
}

return
FALSE;
}

$array = [
"_10fish" => 'xyz',
"_11fish" => [
"_22" => "a", "b", "c"
],
"someFish" => [
'xyz',
'@attributes' => ['type' => 'cod']
]
];

array_explore($array, function(&$value, $key)
{
// Replace key '@attrutes' with '_attributes'
if('@attributes' === $key)
{
renameKey($value, $key, '_attributes');
}

});

print_r($array);
?>

<< Back to user notes page

To Top