问题
I have some arrays like this:
array(
'id' => 1,
'title' => 'title1',
'name' => 'name1',
'count' => 2
)
array(
'id' => 1,
'title' => 'title1',
'name' => 'name2',
'count' => 3
)
array(
'id' => 2,
'title' => 'title2',
'name' => 'name1',
'count' => 2
)
I want to merge them so that arrays with same id
and title
would be merged. The result should be like:
array(
'id' => 1,
'title' => 'title1',
'name' => array('name1', 'name2'),
'count' => array(2, 3)
)
array(
'id' => 2,
'title' => 'title2',
'name' => 'name1',
'count' => 2
)
Or
array(
'id' => 1,
'title' => 'title1',
'name' => 'name1, name2',
'count' => '2, 3'
)
array(
'id' => 2,
'title' => 'title2',
'name' => 'name1',
'count' => 2
)
Or
array(
'id' => 1,
'title' => 'title1',
'name1' => 2,
'name2' => 3
)
array(
'id' => 2,
'title' => 'title2',
'name1' => 2
)
array_merge_recursive()
will expand all the keys, instead of grouping. (All arrays could also be the form of objects.)
Original Problem
Actually it's a query result from MySQL database, where I used COUNT
, GROUP BY
and JOIN
to generate the three arrays above. Since all MySQL queries have the structure of single rows, and the query results cannot contain subgroup type, some result rows have the same id
and title
. For now I'm thinking processing those results in PHP.
If you have some better ideas other than this, please also write it out.
回答1:
Here is the code
<?php
$data=array(array(
'id' => 1,
'title' => 'title1',
'name' => 'name1',
'count' => 2
),
array(
'id' => 1,
'title' => 'title1',
'name' => 'name2',
'count' => 3
),
array(
'id' => 2,
'title' => 'title2',
'name' => 'name1',
'count' => 2
));
$result=array();
foreach($data AS $item)
{
$key=$item['id'].'_'.$item['title'];
if(!isset($result[$key]))
{
$result[$key]=array(
'id'=>$item['id'],
'title'=>$item['title'],
'name'=>array(),
'count'=>array()
);
}
$result[$key]['name'][]=$item['name'];
$result[$key]['count'][]=$item['count'];
}
print_r($result);
and here is the result
Array
(
[1_title1] => Array
(
[id] => 1
[title] => title1
[name] => Array
(
[0] => name1
[1] => name2
)
[count] => Array
(
[0] => 2
[1] => 3
)
)
[2_title2] => Array
(
[id] => 2
[title] => title2
[name] => Array
(
[0] => name1
)
[count] => Array
(
[0] => 2
)
)
)
来源:https://stackoverflow.com/questions/25618777/php-merge-multi-dimensional-arrays-grouping-by-a-certain-key