使用循環的相反,你總是可以拼合到字符串json_encode()
,執行字符串替換,然後json_decode()
回數組:
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);
}
現在,這並不檢查與預先存在的按鍵衝突(很容易的添加一個字符串比較校驗),它可能不適合大規模陣列單一替代的最佳解決方案..但有關陣列壓扁成替換字符串漂亮的部分是它有效地使更換遞歸,因爲在任何深度的比賽都在一個通代替:
$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 2012-04-16 22:45:53
@Nazariy:php不會複製原始參數,直到它被修改(這就是所謂的寫時拷貝,COW)。從這個角度來看,我沒有看到在這種特殊情況下使用引用的任何優勢 – zerkms 2012-04-16 22:47:47
感謝zerkms,一種優雅的方法。 – 2012-04-16 22:50:13