, 당신은 항상 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
@Nazariy : php는 수정 될 때까지 원래 매개 변수를 복사하지 않습니다 (COW (copy-on-write)라고 함). 이 관점에서 나는이 특별한 경우에 참조를 사용하는 것의 어떤 이점도 보지 못했다. – zerkms
고맙다 zerkms, 우아한 접근. –