修改PHP Eloquent Collection

时间:2017-06-26 07:50:32

标签: php json collections eloquent

我用PHP(Eloquent Collection)生成了这个JSON数据

{
   "1498454460": [
      {
         "value_0": 22.7
      },
      {
         "value_2": 23
      }
   ],
   "1498454640": [
      {
         "value_0": 22.8
      },
      {
         "value_1": 53
      },
      {
         "value_2": 23
      }
   ]
}

我的目标是使用PHP将数据转换为此格式:

{
   "timestamp": 1498454460,
   "value_0": 22.7,
   "value_2": 23
},
{
   "timestamp": 1498454640,
   "value_0": 22.8,
   "value_1": 53,
   "value_2": 23
}

我的大脑被锁定所以我无法看到解决方案......:/

1 个答案:

答案 0 :(得分:2)

将json解码为数组,遍历数组并创建所需的结构:

<?php
$json = '
{
   "1498454460": [
      {
         "value_0": 22.7
      },
      {
         "value_2": 23
      }
   ],
   "1498454640": [
      {
         "value_0": 22.8
      },
      {
         "value_1": 53
      },
      {
         "value_2": 23
      }
   ]
}';

$result = array();
foreach (json_decode($json, true) as $key => $value) {
    $item = array();
    $item['timestamp'] = $key;
    foreach ($value as $value2) {
        $item = array_merge($item, $value2);
    }
    $result[] = $item;
}

echo json_encode($result);
die();