PHP深度扩展数组 [英] PHP Deep Extend Array

查看:134
本文介绍了PHP深度扩展数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何对多维关联数组进行深度扩展(与解码的JSON对象一起使用). 我需要等价于 jQuery的$.extend(true, array1, array2) 的php数组,而不是JSON和PHP./p>

这是我需要的一个例子(array_merge_recursive似乎没有做同样的事情)

$array1 = ('1'=> ('a'=>'array1a', 'b'=>'array1b'));
$array2 = ('1'=> ('a'=>'array2a', 'c'=>'array2b'));

$array3 = array_extend($array1, $array2);

//$array3 = ('1'=> ('a'=>'array2a', 'b'=>'array1b', 'c'=>'array2b'))

请注意,如果array2具有相同的值(例如,类的扩展如何工作),它将如何覆盖array1

解决方案

如果您使用的是PHP 5.3.0+,则可以使用jQuery's $.extend(true, array1, array2) with arrays instead of JSON and in PHP.

Here's an example of what I need (array_merge_recursive didn't seem to do the same thing)

$array1 = ('1'=> ('a'=>'array1a', 'b'=>'array1b'));
$array2 = ('1'=> ('a'=>'array2a', 'c'=>'array2b'));

$array3 = array_extend($array1, $array2);

//$array3 = ('1'=> ('a'=>'array2a', 'b'=>'array1b', 'c'=>'array2b'))

Notice how array2 overrides array1 if it has same value (like how extension of classes works)

解决方案

If you have PHP 5.3.0+, you can use array_replace_recursive which does exactly what you need:

array_replace_recursive() replaces the values of array1 with the same values from all the following arrays. If a key from the first array exists in the second array, its value will be replaced by the value from the second array. If the key exists in the second array, and not the first, it will be created in the first array. If a key only exists in the first array, it will be left as is. If several arrays are passed for replacement, they will be processed in order, the later array overwriting the previous values.

这篇关于PHP深度扩展数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆