我有一个数组,它包含数据库中的一组信息,但其中一些是重复的,数组最深处只有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’]值放入一个数组中,如下所示:
[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;
}
?>
基本上我要问的是:如何在多维数组中找到重复项,然后将每个重复项放入自己的数组中?
$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
阵列的键,可以选择后面跟一个$result = array_values($result)
。