PHP如何将数组组织成组但保持顺序?
我想通过PHP如何将数组组织成组但保持顺序?,php,arrays,Php,Arrays,我想通过id, 但仍然保留订单,这意味着它可能有重复的组, 比如: 数组: array ( 0 => array ( 'id' => 1, 'message' => 'AAA', 'sent_on' => 1582097767 ), 1 => array ( 'id' => 2, 'message' => 'AAAQAW', 'sent_on' => 1582097770
id
,但仍然保留订单,这意味着它可能有重复的组, 比如: 数组:
array (
0 =>
array (
'id' => 1,
'message' => 'AAA',
'sent_on' => 1582097767
),
1 =>
array (
'id' => 2,
'message' => 'AAAQAW',
'sent_on' => 1582097770
),
2 =>
array (
'id' => 2,
'message' => 'dqwdq',
'sent_on' => 1582097772
),
3 =>
array (
'id' => 1,
'message' => 'dqwdq',
'sent_on' => 1582097773
),
4 =>
array (
'id' => 1,
'message' => 'wq',
'sent_on' => 1582097773
),
5 =>
array (
'id' => 2,
'message' => 'd',
'sent_on' => 1582097774
),
6 =>
array (
'id' => 1,
'message' => 'dew',
'sent_on' => 1582112219
)
)
希望的结果:
array (
0 =>
array (
0 =>
array (
'id' => 1,
'message' => 'AAA',
'sent_on' => 1582097767
),
),
1 =>
array (
0 =>
array (
'id' => 2,
'message' => 'AAAQAW',
'sent_on' => 1582097770
),
1 =>
array (
'id' => 2,
'message' => 'dqwdq',
'sent_on' => 1582097772
)
),
2 =>
array (
0 =>
array (
'id' => 1,
'message' => 'dqwdq',
'sent_on' => 1582097773
),
1 =>
array (
'id' => 1,
'message' => 'wq',
'sent_on' => 1582097773
)
),
3 =>
array (
0 =>
array (
'id' => 2,
'message' => 'd',
'sent_on' => 1582097774
)
),
4 =>
array (
0 =>
array (
'id' => 1,
'message' => 'dew',
'sent_on' => 1582112219
)
)
)
是的,使用
array\u reduce
可以很容易地完成:
$lastCheckedItem = ['id' => 0];
$finalArray = array_reduce($array, static function(array $carry, array $item) use (&$lastCheckedItem) {
if ($lastCheckedItem['id'] === $item['id'] && !empty($carry)) {
$lastKey = array_key_last($carry);
$carry[$lastKey][] = $item;
}
else {
$carry[] = [$item];
}
$lastCheckedItem = $item;
return $carry;
}, []);
aa还有什么问题?@matit呃,是的,我只知道如何将数组分成两组,如
id=1
,id=2
,但我希望它需要有五组谢谢!!!很好的回答!!顺便问一下,为什么数组名是$carry
lolyw。因为它在每次迭代中都会带上设定的值,直到循环结束。明白了。它让我笑了,因为它是我爸爸给我的英文昵称。。自从你问起我就注意到了:)
$lastCheckedItem = ['id' => 0];
$finalArray = array_reduce($array, static function(array $carry, array $item) use (&$lastCheckedItem) {
if ($lastCheckedItem['id'] === $item['id'] && !empty($carry)) {
$lastKey = array_key_last($carry);
$carry[$lastKey][] = $item;
}
else {
$carry[] = [$item];
}
$lastCheckedItem = $item;
return $carry;
}, []);