首页 > 解决方案 > 如何在php中将多个数组或json合并为一个?

问题描述

背景

这是一个 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()来获取所有的 JSON 内容$urls

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 对象合并为一个?

接受任何建议,感谢您对此的关注。

标签: phparraysjson

解决方案


感谢@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()不太熟悉,从现在开始这应该很简单。


推荐阅读