我有一些像这样的数组:
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 )我想合并它们,以便合并具有相同 id 和 title 的数组.结果应为:
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 )或
array( 'id' => 1, 'title' => 'title1', 'name' => 'name1, name2', 'count' => '2, 3' ) array( 'id' => 2, 'title' => 'title2', 'name' => 'name1', 'count' => 2 )或
array( 'id' => 1, 'title' => 'title1', 'name1' => 2, 'name2' => 3 ) array( 'id' => 2, 'title' => 'title2', 'name1' => 2 )array_merge_recursive()将展开所有键,而不是分组.(所有数组也可以是对象的形式.)
array_merge_recursive() will expand all the keys, instead of grouping. (All arrays could also be the form of objects.)
原始问题
实际上这是来自MySQL数据库的查询结果,我在其中使用 COUNT , GROUP BY 和 JOIN 生成了上面的三个数组.由于所有MySQL查询都具有单行结构,并且查询结果不能包含子组类型,因此某些结果行具有相同的 id 和 title .现在,我正在考虑在PHP中处理这些结果.
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.
推荐答案下面是代码
<?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);这是结果
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 ) ) )更多推荐
PHP:合并多维数组,按特定键分组
发布评论