【问题标题】:How to merge multiple arrays or json into one in php?如何在php中将多个数组或json合并为一个?
【发布时间】:2021-09-07 15:16:38
【问题描述】:

背景

这是一个 WordPress 插件开发问题。

有一个 API 在数组中返回动态 url 地址:

array(4) {
[0]=>string(22) "https://t.somedomain.com"
[1]=>string(20) "https://somedomain.com"
[2]=>string(23) "http://192.168.2.209/km"
[3]=>string(23) "http://somedomain2/km"
....
}

我已经能够重新遍历上面的数组并将其保存到 php $urls 中,

上面的每个url地址都可以在GET它之后返回一个JSON响应,就像我GET一个url它会响应如下:

{
    "name":"HR",
    "floor":3,
    "staff": [
        { "name":"John", "info":[ "Java", "Google", "Market" ] },
        { "name":"Alex", "info":[ "PHP", "Swift", "Market" ] },
        { "name":"Duke", "info":[ "HTML", "Market" ] }
    ]
}

目标

从所有url中获取所有json内容并合并为一个,并将这些json解码,以便php操作这些数据。

目前的进展

由于现在所有 url 都存储在变量 $urls 中,我可以使用 foreach() 来获取所有 $urls 中的 JSON 内容。

foreach ( $urls as $url ){
    $response = wp_remote_retrieve_body( wp_remote_get( $url ) );
    $obj = json_decode( $response );
    // var_dump( $obj );
}

这将返回所有 url 的结果,但一一分开。

因为url会发生变化,而且url可能会很多,所以不宜使用:

array_merge($array1, $array2);

问题

有没有可能将每个$response(json) 合并为一个?

或者有没有可能将每个解码的 php 对象合并为一个?

欢迎提出任何建议,感谢您对此的关注。

【问题讨论】:

  • 您应该合并解码的响应,而不是 JSON。
  • 您希望合并后的结果是什么样的?它应该如何处理结果中的重复键?
  • @Barmar 对!谢谢!但是怎么做呢?
  • @Barmar 在我的情况下不会有重复的,谢谢你我会挖掘链接:)

标签: php arrays json


【解决方案1】:

感谢@Barmar,我把这个问题想得太复杂了,经过尝试和尝试,我找到了解决方案:

    $merged = array(); 
//Here to declear this $merged is an array.

    foreach ( $urls as $url ){
        $response = wp_remote_retrieve_body( wp_remote_get( $url ) );
        $obj = json_decode( $response );
            if(is_array($obj)){  //prevent empty or error ones goes to next step
                $merged = array_merge($merged,$obj);
//Yes still have to use arrary_merge() function, add one to $merged after another 
//till the loop is end. 
//So $merged will contain all the decoded json data.

            }
    }
    $result = json_encode($merged); 

//This is an example we can now deal with $merged with php, 
//sort, insert, modify staff... 
//here I transcoded $merged to a JSON again for further output.

上面的代码正在运行。 对array_merge()不太熟悉,以后应该会很简单。

【讨论】:

    猜你喜欢
    • 2013-12-25
    • 2019-01-03
    • 2021-11-21
    • 2019-03-01
    • 1970-01-01
    • 2017-10-04
    • 1970-01-01
    相关资源
    最近更新 更多