【问题标题】:how to push nested array in one array如何将嵌套数组推入一个数组
【发布时间】:2021-02-26 05:19:26
【问题描述】:

如何在数组的嵌套对象中基于排序连接数据 我有这样的数据对象:

{
  "data": [
     {
        "id": "1",
     },
     {
        "id": "2",
     },
 ],
 "includes": {
     "users": [
         {
            "name": "Ronni Herdi"
         },
         {
            "name": "Floridamaya2"
         },
  
    ],
    "tweets": [
          {
             "created_at": "2021-02-26T01:08:42.000Z"
          },
         {
             "created_at": "2021-02-26T01:46:27.000Z"
         }
    ]
  }
}

如何基于排序加入数据使数据数组在一个数组中,我想要这样的结果:

{
    "data": [
         {
            "id": "1",
            "name": "Ronni Herdi",
            "created_at": "2021-02-26T01:08:42.000Z"
         },
         {
           "id": "2",
           "name": "Floridamaya2",
           "created_at": "2021-02-26T01:46:27.000Z"
         }
    ]
}

我该怎么做...?

【问题讨论】:

  • 有人能解释一下我在php中怎么做吗?

标签: php arrays laravel


【解决方案1】:

只需循环数据并将项目附加到新的关联数组:

$input_json = ''; // json from post

$input = json_decode($input_json, true);

$joined = [];
foreach($input['data'] as $i => $item) {
  $joined[] = array_merge(
     $item, 
     $input['includes']['users'][$i], 
     $input['includes']['tweets'][$i]
  );
}
$output = ['data' => $joined];
print_r($output);

http://sandbox.onlinephpfunctions.com/code/feb743acd25f4dfa9674d18b74d9d2a5d6b6a78f

【讨论】:

  • 问题被标记为PHP,那为什么你提供的答案不是PHP而是JavaScript呢?
  • @Striezel 哎呀,没有意识到它被标记为 php。
  • @Striezel 改为 php
  • 谢谢你内森
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-10
  • 2022-01-03
  • 1970-01-01
  • 2018-06-26
  • 1970-01-01
相关资源
最近更新 更多