我有一个数组,其中包含来自数据库的一组信息,但其中一些是重复的,在更改的数组的最深部分只有1个值。例如:
[0] => Array( ['id'] => 1 , ['name'] => "First Array" , ['more'] => "stuff" )
[1] => Array( ['id'] => 2 , ['name'] => "Second Array" , ['more'] => "stuff1" )
[2] => Array( ['id'] => 2 , ['name'] => "Second Array" , ['more'] => "stuff2" )
[3] => Array( ['id'] => 3 , ['name'] => "Third Array" , ['more'] => "stuff3" )
[4] => Array( ['id'] => 3 , ['name'] => "Third Array" , ['more'] => "stuff4" )
我要做的是将具有相同['id']字段的任何数组放入具有数组而不是['more']的数组中。例如:
[0] => Array( ['id'] => 1 , ['name'] => "First Array" , ['more'] => "stuff" )
[1] => Array( ['id'] => 2 , ['name'] => "Second Array" , ['more'] => Array( [0] => "stuff1" , [1] => "stuff2" ) )
[2] => Array( ['id'] => 2 , ['name'] => "Third Array" , ['more'] => Array( [0] => "stuff3" , [1] => "stuff4" ) )
我试过这几种方法,但我能得到的最接近的函数是将所有['more']值放入1个数组中:
[0] => Array( ['id'] => 1 , ['name'] => "First Array" , ['more'] => "stuff" )
[1] => Array( ['id'] => 2 , ['name'] => "Second Array" , ['more'] => Array( [0] => "stuff1" , [1] => "stuff2" , [2] => "stuff3" , [3] => "stuff4" ) )
这是来自这个功能:
<?php
private function compress_duplicates( $a = array() ) {
$diff_key = array_diff_key( $a , array_unique( $a ) );
$first_key = array_shift(array_keys($diffkey));
$array["id"] = $diff_key[$first_key]["id"];
$array["name"] = $diff_key[$first_key]["name"];
foreach($diff_key as $term) {
$array["more"][] = $term["more"];
}
return $array;
}
?>
基本上我要问的是:如何在多维数组中找到重复项,然后将每个重复项放入自己的数组中?
答案 0 :(得分:2)
$result = array();
foreach ($array as $elem) {
if (isset($result[$elem['id']])) {
$result[$elem['id']]['more'] = array_merge((array)$result[$elem['id']]['more'],
array($elem['more']));
} else {
$result[$elem['id']] = $elem;
}
}
如果要重置$result = array_values($result)
数组的键,可选择后跟$result
。