使用PHP循环JSON并生成嵌套JSON的新格式

时间:2017-05-05 10:08:25

标签: php arrays json key

在PHP中,如何循环使用以下JSON对象的日期键,如果日期值相同则合并时间:

[
  {
    date: "27-06-2017",
    time: "1430"
  },
  {
    date: "27-06-2017",
    time: "1500"
  },
  {
    date: "28-06-2017",
    time: "0930"
  },
  {
    date: "28-06-2017",
    time: "0915"
  }
] 

结果应如下所示:

[
  {
    date: "27-06-2017",
    time: [{"1430","1500"}]
  },      {
    date: "28-06-2017",
    time: [{"0930, 0915"}]
  }
] 

我应该创建一个空数组,然后循环通过JSON并重新创建一个新的JSON?有没有更好的方法或任何解决方案可供参考?

谢谢!

5 个答案:

答案 0 :(得分:1)

请试试这个:

$a = [] // Your input array
$op= [];//output array
foreach($a as $key => $val){
    $key = $val['date'];
    $op[$key][] = $val['time'];
}
$op2 = [];
foreach($op as $key => $val){
    $op2[] = ['date' => $key, 'time' => $val]; 
}

答案 1 :(得分:1)

另一个想法是

<?php
    $string = '[{"date": "27-06-2017","time": "1430"},{"date": "27-06-2017","time": "1500"},{"date": "28-06-2017","time": "0930"},{"date": "28-06-2017","time": "0915"}]';
    $arrs = json_decode($string);
    $main = array();
    $temp = array();
    foreach($arrs as $arr){
      if(in_array($arr->date,$temp)){
        $main[$arr->date]['time'][] = $arr->time;
      }else{
        $main[$arr->date]['date'] = $arr->date;
        $main[$arr->date]['time'][] = $arr->time;
        $temp[] = $arr->date;
      }
    }
    echo json_encode($main);
?>

现场演示:https://eval.in/787695

答案 2 :(得分:1)

// create the "final" array
$final = [];

// loop the JSON (assigned to $l)
foreach($l as $o) {

    // assign $final[{date}] = to be a new object if it doesn't already exist
    if(empty($final[$o->date])) {
        $final[$o->date] = (object) ['date' => $o->date, 'time' => [$o->time]];
    }

    // ... otherwise, if it does exist, just append this time to the array
    else {
        $final[$o->date]->time[] = $o->time;
    }
}

// to get you back to a zero-indexed array
$final = array_values($final);

最初使用基于日期的索引创建&#34; final&#34; 数组,以便您可以确定是否已设置它们以允许您操作正确的< em>&#34;时间&#34; 数组。

最后通过将$final放入array_values()来删除它们,以获得您之后的零索引数组。

json_encode($final)会让你想要一个JSON:

[{"date":"27-06-2017","time":["1430","1500"]},{"date":"28-06-2017","time":["0930","0915"]}]

答案 3 :(得分:1)

此解决方案有点开销,但如果您确定数据是连续的和已排序的,则可以使用array_count_valuesarray_map

NULL ID

这是working demo

答案 4 :(得分:1)

又一个解决方案:

$d = [];
$dizi = array_map(function ($value) use (&$d) {
    if (array_key_exists($value->date, $d)) {
        array_push($d[$value->date]['time'], $value->time);
    } else {
        $d[$value->date] = [
            'date' => $value->date,
            'time' => [$value->time]
        ];
    }
}, $array);
echo json_encode(array_values($d));