PHP find values from a multidimensional array and then place them in an array
I have an array which contains a set of information from a database, but some of it is a duplicate with just 1 value in the deepest part of the array changed. For example:
[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" )
What I'm trying to do is get any arrays with the same ['id'] field into an array with an array instead of ['more']. For example:
[0] => Array( ['id'] => 1 , ['name'] => "First Array" , ['more'] => 开发者_Python百科"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" ) )
I have tried to do this a few ways, but the closest I can get is a function which will put all the ['more'] values into 1 array like this:
[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" ) )
And that is from this function:
<?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;
}
?>
Basically what I'm asking: How can I find duplicates in a multidimensional array and then place each of those duplicates into their own 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;
}
}
Optionally followed by a $result = array_values($result)
if you want to reset the keys of the $result
array.
精彩评论