繁体   English   中英

PHP如何将数组组织成组但保持顺序?

[英]PHP How to organize array into groups but keep the order?

我想按id将数组分组,
但仍然保留订单,这意味着它可能有重复的组,例如:

Group1 [id: 1]
Group2 [id: 2]
Group3 [id: 1]
....
...
..
.

大批:

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_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;
}, []);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM