多维数组PHP合并重复的数组值 [英] merge duplicate array values in a multidimensional array php
本文介绍了多维数组PHP合并重复的数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个多维数组说,
Array
(
[0] => Array
(
[id] => 1
[email_id] => ok@gmail.com
[password] => test
)
[1] => Array
(
[id] => 2
[email_id] => check@gmail.com
[password] => test
)
[2] => Array
(
[id] => 3
[email_id] => an@gmail.com
[password] => pass
)
)
下面上述阵列中,密码键有两个键相同的值,我需要合并具有重复值得到下面的输出数组,
Here in the above array, password key has same value in two keys, i need to merge the arrays which have duplicate values to get the following output,
Array
(
[0] => Array
(
[0] => Array
(
[id] => 1
[email_id] => ok@gmail.com
[password] => test
)
[1] => Array
(
[id] => 2
[email_id] => check@gmail.com
[password] => test
)
)
[1] => Array
(
[id] => 3
[email_id] => an@gmail.com
[password] => pass
)
)
如何做到这一点?我试过array_merge&安培; foreach循环,但我不能得到这个输出
How to do this ? i've tried array_merge & foreach loops, but i can't get this output
推荐答案
尝试,
$arr = array( array('id'=>1, 'email_id'=>'ok@gmail.com', 'password'=>'test'),
array('id'=>2, 'email_id'=>'check@gmail.com', 'password'=>'test'),
array('id'=>3, 'email_id'=>'an@gmail.com', 'password'=>'pass'));
$new_arr = array();
foreach($arr as $k => $v) {
if( is_array($arr[$k+1]) && $arr[$k]['password'] === $arr[$k + 1]['password'] )
$new_arr[] = array($arr[$k], $arr[$k+1]);
else if( in_array_recursive($arr[$k]['password'], $new_arr) === FALSE )
$new_arr[] = $v;
}
function in_array_recursive( $val, $arr) {
foreach( $arr as $v ) {
foreach($v as $m) {
if( in_array($val, $m ) )
return TRUE;
}
}
return FALSE;
}
print_r($new_arr);
这篇关于多维数组PHP合并重复的数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文