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);
}
});
}
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);
$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)
{
if('@attributes' === $key)
{
renameKey($value, $key, '_attributes');
}
});
print_r($array);
?>