【问题标题】:PHP combine multiple arrays into one single entityPHP 将多个数组组合成一个实体
【发布时间】:2014-04-25 09:44:58
【问题描述】:

array1 看起来像这样

 $array1 = [{
        'id': 1,
            'name': 'John'
    }]

这里是array2:

$array2 = [{
    'id': 1,
        'name': 'someone'
}, {
    'id': 1,
        'name': 'Rocky'
}, {
    'id': 1,
        'name': 'Samuel'
}]

我想要这样的东西:

$array1combinedwitharray2 = [{
    'id': 1,
        'name': 'John'
}, {
    'id': 1,
        'name': 'someone'
}, {
    'id': 1,
        'name': 'Rocky'
}, {
    'id': 1,
        'name': 'Samuel'
}

]

我尝试了几次,结果数组进入另一个数组。

【问题讨论】:

标签: php arrays json function output


【解决方案1】:

似乎这些是 JSON 数据,所以使用 json_decode() 对其进行解码,最后使用 json_encode() 作为包装器进行 array_merge()

代码..

$array1combinedwitharray2 = json_encode(array_merge(json_decode($array1,true),json_decode($array2,true)));

【讨论】:

  • json_decode() 期望参数 1 是字符串,给定数组
  • 那么就用$array1combinedwitharray2 = array_merge($array1,$array2); echo json_encode($array1combinedwitharray2);代替上面的代码。
【解决方案2】:

【讨论】:

    【解决方案3】:

    这些是 JSON 对象,首先您需要将它们转换为数组,然后将它们合并,然后编码为 JSON 格式。

    $array1combinedwitharray2 = json_encode(array_merge(json_decode($array1,true),json_decode($array2,true)));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多