简体   繁体   English

使用PHP将具有相似日期的元素分组到数组中

[英]Group element with similar date into an array with PHP

I need to merge datas from an array with PHP. 我需要使用PHP合并数组中的数据。

Supposing I have this array: 假设我有这个数组:

Array
(
    [0] => Array
        (
            [date] => 2018-03-26
            [person] => 120.00
            [color] => Black
        )
    [1] => Array
        (
            [date] => 2018-03-26
            [person] => 120.00
            [color] => Yellow
        )
    [2] => Array
        (
            [date] => 2018-03-27
            [person] => 120.00
            [color] => Red
        )
)

How I can merge datas with similar date to have something like this ? 我如何合并具有相似日期的数据以具有这样的功能?

Array
(
    [0] => Array
        (
            [2018-03-26] => Array
            (
                [0] => Array
                (
                    [person] => 120.00
                    [color] => Black
                )
                [1] => Array
                (
                    [person] => 120.00
                    [color] => Yellow
                )
            )
        )
    [1] => Array
        (
            [2018-03-27] => Array
            (
                [0] => Array
                (
                    [person] => 120.00
                    [color] => Red
                )
            )
        )
)

This is what I tried by reading some documentation over SO and Google: 这是我通过阅读SO和Google的一些文档来尝试的:

$newArray = array();
foreach ($initialArray as $item) {
    if (!empty($newArray[$item['date']])) {
        $currentValue = $newArray[$item['date']];
        $newArray[$item['date']]['person'] = $item['person'];
        $newArray[$item['date']]['color'] = $item['color'];
    } else {
        $newArray[$item['date']] = $item;
    }
}

What I missing here please ? 我在这里想念的是什么?

Thanks. 谢谢。

I found another solution: 我找到了另一个解决方案:

$return = array();
foreach($datas as $val) {
    if (!isset($return[$val['date']])) {
        $return[$val['date']] = array();
    }
    $return[$val['date']][] = $val;
}

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

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