PHP JSON Array - Group by the same value

后端 未结 2 407
故里飘歌
故里飘歌 2021-01-14 17:00

I\'m thinking how to group my array by objects with the same value.

I have this result from MySQL query:

   Date           StartTime           EndTim         


        
2条回答
  •  情话喂你
    2021-01-14 17:51

    Based on the structure outlined in the question:

    Requires php 5.4+ for the json pretty printing, if you are on a lower version just remove it and use long array format.

    $in = <<<'JSON'
    [
        {
            "Date": "2014-12-01",
            "StartTime": "10:00",
            "EndTime": "16:00"
        },
        {
            "Date": "2014-12-02",
            "StartTime": "12:00",
            "EndTime": "18:00"
        },
        {
            "Date": "2014-12-03",
            "StartTime": "10:00",
            "EndTime": "20:00"
        },
        {
            "Date": "2014-12-03",
            "StartTime": "12:00",
            "EndTime": "20:00"
        }
    ]
    JSON;
    
    $data = json_decode($in, true);
    $out = [];
    
    foreach($data as $element) {
            $out[$element['Date']][] = ['StartTime' => $element['StartTime'], 'EndTime' => $element['EndTime']];
    }
    
    var_dump(json_encode($out, JSON_PRETTY_PRINT));
    

    To get the exact same output as in the question (the returned output wrapped in a single element json-array you'd need to wrap $out in an other array like this:

    json_encode([$out], JSON_PRETTY_PRINT)

    Results in:

    {
      "2014-12-01": [
        {
          "StartTime": "10:00",
          "EndTime": "16:00"
        }
      ],
      "2014-12-02": [
        {
          "StartTime": "12:00",
          "EndTime": "18:00"
        }
      ],
      "2014-12-03": [
        {
          "StartTime": "10:00",
          "EndTime": "20:00"
        },
        {
          "StartTime": "12:00",
          "EndTime": "20:00"
        }
      ]
    }
    

提交回复
热议问题