、いつでも戻って、アレイにjson_decode()
その後、json_encode()
で文字列に平らに文字列置換を行うことができます:
を
function replaceKey($array, $old, $new)
{
//flatten the array into a JSON string
$str = json_encode($array);
// do a simple string replace.
// variables are wrapped in quotes to ensure only exact match replacements
// colon after the closing quote will ensure only keys are targeted
$str = str_replace('"'.$old.'":','"'.$new.'":',$str);
// restore JSON string to array
return json_decode($str, TRUE);
}
さて、これは(文字列の比較チェックを追加して簡単に十分な)既存のキーとの競合をチェックしません、それは大規模な配列における単一の置換のための最善の解決策ではないかもしれません..しかし、交換のための文字列に配列を平坦化についての素晴らしい部分は、任意の深さでの試合はすべて1回のパスで置き換えられているので、それが効果的に交換用の再帰的になるということです。私の中
$arr = array(
array(
'name' => 'Steve'
,'city' => 'Los Angeles'
,'state' => 'CA'
,'country' => 'USA'
,'mother' => array(
'name' => 'Jessica'
,'city' => 'San Diego'
,'state' => 'CA'
,'country' => 'USA'
)
)
,array(
'name' => 'Sara'
,'city' => 'Seattle'
,'state' => 'WA'
,'country' => 'USA'
,'father' => array(
'name' => 'Eric'
,'city' => 'Atlanta'
,'state' => 'GA'
,'country' => 'USA'
,'mother' => array(
'name' => 'Sharon'
,'city' => 'Portland'
,'state' => 'OR'
,'country' => 'USA'
)
)
)
);
$replaced = replaceKey($arr,'city','town');
print_r($replaced);
出力
Array
(
[0] => Array
(
[name] => Steve
[town] => Los Angeles
[state] => CA
[country] => USA
[mother] => Array
(
[name] => Jessica
[town] => San Diego
[state] => CA
[country] => USA
)
)
[1] => Array
(
[name] => Sara
[town] => Seattle
[state] => WA
[country] => USA
[father] => Array
(
[name] => Eric
[town] => Atlanta
[state] => GA
[country] => USA
[mother] => Array
(
[name] => Sharon
[town] => Portland
[state] => OR
[country] => USA
)
)
)
)
非常に興味深いアプローチ、意見を参考に配列を渡す方が良いでしょう。 – Nazariy
@ Nazariy:phpは元のパラメータが変更されるまでコピーされません(コピーオンライト、COW)。このような観点から、この特定のケースでは参照を使用する利点はありません – zerkms
ありがとうございますzerkms、優雅なアプローチ。 –