php php数组组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12706359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php array group
提问by Red
I have the following array
我有以下数组
Array
(
[0] => Array
(
[id] => 96
[shipping_no] => 212755-1
[part_no] => reterty
[description] => tyrfyt
[packaging_type] => PC
)
[1] => Array
(
[id] => 96
[shipping_no] => 212755-1
[part_no] => dftgtryh
[description] => dfhgfyh
[packaging_type] => PC
)
[2] => Array
(
[id] => 97
[shipping_no] => 212755-2
[part_no] => ZeoDark
[description] => s%c%s%c%s
[packaging_type] => PC
)
)
How can I group the array by id? Is there any native php functions are available to do this?
如何将数组分组id?是否有任何本机 php 函数可用于执行此操作?
If I foreachthe above then I will get a duplicate one, how can I avoid that?
如果我foreach以上,那么我会得到一个重复的,我怎样才能避免这种情况?
On the above example idhave 2 items, so its need to be inside of the id.
在上面的例子中id有 2 个项目,所以它需要在id.
EDIT : EVERYTHING WORKS FINE : BUT IS THERE ANY WAY TO ACHIEVE THE SAME WITH ONE FOREACH ?
编辑:一切正常:但是有什么方法可以通过一个 FOREACH 实现相同的目标吗?
回答by xdazz
There is no native one, just use a loop.
没有原生的,只需使用循环。
$result = array();
foreach ($data as $element) {
$result[$element['id']][] = $element;
}
回答by Baba
You can try the following:
您可以尝试以下操作:
$group = array();
foreach ( $array as $value ) {
$group[$value['id']][] = $value;
}
var_dump($group);
Output:
输出:
array
96 =>
array
0 =>
array
'id' => int 96
'shipping_no' => string '212755-1' (length=8)
'part_no' => string 'reterty' (length=7)
'description' => string 'tyrfyt' (length=6)
'packaging_type' => string 'PC' (length=2)
1 =>
array
'id' => int 96
'shipping_no' => string '212755-1' (length=8)
'part_no' => string 'dftgtryh' (length=8)
'description' => string 'dfhgfyh' (length=7)
'packaging_type' => string 'PC' (length=2)
97 =>
array
0 =>
array
'id' => int 97
'shipping_no' => string '212755-2' (length=8)
'part_no' => string 'ZeoDark' (length=7)
'description' => string 's%c%s%c%s' (length=9)
'packaging_type' => string 'PC' (length=2)
回答by atomrc
In a more functional programming style, you could use array_reduce
在更函数式的编程风格中,您可以使用 array_reduce
$groupedById = array_reduce($data, function (array $accumulator, array $element) {
$accumulator[$element['id']][] = $element;
return $accumulator;
}, []);
回答by AndyClaw
I just threw this together, inspired by .NET LINQ
我只是把它放在一起,灵感来自 .NET LINQ
<?php
// callable type hint may be "closure" type hint instead, depending on php version
function array_group_by(array $arr, callable $key_selector) {
$result = array();
foreach ($arr as $i) {
$key = call_user_func($key_selector, $i);
$result[$key][] = $i;
}
return $result;
}
$data = array(
array(1, "Andy", "PHP"),
array(1, "Andy", "C#"),
array(2, "Josh", "C#"),
array(2, "Josh", "ASP"),
array(1, "Andy", "SQL"),
array(3, "Steve", "SQL"),
);
$grouped = array_group_by($data, function($i){ return $i[0]; });
var_dump($grouped);
?>
And voila you get
瞧你得到
array(3) {
[1]=>
array(3) {
[0]=>
array(3) {
[0]=>
int(1)
[1]=>
string(4) "Andy"
[2]=>
string(3) "PHP"
}
[1]=>
array(3) {
[0]=>
int(1)
[1]=>
string(4) "Andy"
[2]=>
string(2) "C#"
}
[2]=>
array(3) {
[0]=>
int(1)
[1]=>
string(4) "Andy"
[2]=>
string(3) "SQL"
}
}
[2]=>
array(2) {
[0]=>
array(3) {
[0]=>
int(2)
[1]=>
string(4) "Josh"
[2]=>
string(2) "C#"
}
[1]=>
array(3) {
[0]=>
int(2)
[1]=>
string(4) "Josh"
[2]=>
string(3) "ASP"
}
}
[3]=>
array(1) {
[0]=>
array(3) {
[0]=>
int(3)
[1]=>
string(5) "Steve"
[2]=>
string(3) "SQL"
}
}
}
回答by AndyClaw
I needed such function too. I created this one, you pass which column you want to group by:
我也需要这样的功能。我创建了这个,你通过你想要分组的列:
function array_group(array $data, $by_column)
{
$result = [];
foreach ($data as $item) {
$column = $item[$by_column];
unset($item[$by_column]);
if (isset($result[$column])) {
$result[$column][] = $item;
} else {
$result[$column] = array($item);
}
}
return $result;
}
回答by Amrish Prajapati
for($i = 0 ; $i < count($arr) ; $i++ )
{
$tmpArr[$arr[$i]['id']] = $arr[$i]['id'];
}
$vmpArr = array_keys($tmpArr);
print_r($vmpArr);
回答by Jake Z
This array_group_byfunction achieves what you are looking for:
这个array_group_by函数实现了你想要的:
$grouped = array_group_by($arr, 'id');
It even supports multi-level groupings:
它甚至支持多级分组:
$grouped = array_group_by($arr, 'id', 'part_no');
回答by Athari
It's trivial to do with LINQ, which is implemented in PHP in several libraries, including YaLinqo*. It allows performing SQL-like queries on arrays and objects. The groubByfunction is designed specifically for grouping, you just need to specify the field you want to group by:
使用 LINQ 很简单,它在 PHP 中的几个库中实现,包括YaLinqo*。它允许对数组和对象执行类似 SQL 的查询。该groubBy函数专为分组而设计,您只需要指定要分组的字段:
$grouped_array = from($array)->groupBy('$v["id"]')->toArray();
Where '$v["id"]'is a shorthand for function ($v) { return $v["id"]; }which this library supports.
这个库支持'$v["id"]'的简写在哪里function ($v) { return $v["id"]; }。
The result will be exactly like in the accepted answer, just with less code.
结果将与接受的答案完全一样,只是代码更少。
* developed by me
* 由我开发
回答by rwhite
Expanding on @baba's answer, which I like, but creates a more complex three level deep multi-dimensional (array(array(array))):
扩展我喜欢的@baba 的答案,但创建了一个更复杂的三级深度多维(数组(数组(数组))):
$group = array();
foreach ( $array as $value ) {
$group[$value['id']][] = $value;
}
// output only data from id 96
foreach ($group as $key=>$value) { //outer loop
foreach ($value as $k=>$v){ //inner loop
if($key==96){ //if outer loop is equal to 96 (could be variable)
for ($i=0;$i<count($k);$i++){ //iterate over the inner loop
printf($key.' has a part no. of '.$v['part_no'].' and shipping no. of '.$v['shipping_no'].'<br>');
}
}
}
}
Will output:
将输出:
96 has a part no. of reterty and shipping number of 212755-1
96 有一个零件号。reterty 和 212755-1 的运输号码
96 has a part no. of dftgtryh and shipping number of 212755-1
96 有一个零件号。dftgtryh 和发货编号 212755-1
回答by Sebass van Boxel
$arr = array();
foreach($old_arr as $key => $item)
{
$arr[$item['id']][$key] = $item;
}
ksort($arr, SORT_NUMERIC);

