【问题标题】:Modify PHP Eloquent Collection修改 PHP Eloquent 集合
【发布时间】:2017-06-26 07:50:32
【问题描述】:

我有这个用 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
}

我的大脑被锁住了,所以我看不到解决方案...:/

【问题讨论】:

  • 你在 Laravel,对吧?如果您将集合作为对象,则可以使用flatten helper method
  • Laravel 是的!扁平化助手不起作用....我认为

标签: php json collections eloquent


【解决方案1】:

将 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();

【讨论】:

    猜你喜欢
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    • 2010-11-12
    • 2017-03-26
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多