PHP:合并多维数组,按特定键分组

编程入门 行业动态 更新时间:2024-10-25 00:25:14
本文介绍了PHP:合并多维数组,按特定键分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一些像这样的数组:

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:合并多维数组,按特定键分组

本文发布于:2023-10-17 10:27:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1500644.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多维   数组   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!