【问题标题】:array_merge(): Argument #1 is not an arrayarray_merge():参数 #1 不是数组
【发布时间】:2017-06-29 06:26:29
【问题描述】:

在这方面需要您的帮助...我的 array_merge 出现错误 这是我的代码:

//first
    $url1="https://www.zopim.com/api/v2/chats";
    $ch1 = curl_init();
    curl_setopt($ch1, CURLOPT_URL, $url1);
    curl_setopt($ch1, CURLOPT_USERPWD, "$username:$password");
    curl_setopt($ch1, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
    $output1 = curl_exec($ch1);
    $info1 = curl_getinfo($ch1);
    curl_close($ch1);

    $chats1 = json_decode($output1,true);

    //second
    $url2="https://www.zopim.com/api/v2/chats?page=2";
    $ch2 = curl_init();
    curl_setopt($ch2, CURLOPT_URL, $url2);
    curl_setopt($ch2, CURLOPT_USERPWD, "$username:$password");
    curl_setopt($ch2, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch2, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
    $output2 = curl_exec($ch2);
    $info2 = curl_getinfo($ch2);
    curl_close($ch2);

    $chats2 = json_decode($output2,true);



    $r = [];
    if(is_array($chats1) && is_array($chats2))
    {
        foreach($chats1 as $key => $array)
        {
            $r[$key] = array_merge($chats2[$key], $array);
        }
    }
    else
    {
    echo 'problem with json';
    }
    echo json_encode($r, JSON_UNESCAPED_SLASHES);

我需要使用 array_merge() 组合两个 json...我使用 curl 授权来调用我的 API..

但是当我尝试运行代码时出现错误:

这是 44 号错误:

【问题讨论】:

  • 不知道第 42 行是哪一行,但您的两个输出变量之一似乎不包含编码对象或数组。
  • 第42行是哪一个?

标签: php json api curl array-merge


【解决方案1】:

这意味着您的json_decode 失败。如果字符串不是有效的 JSON,它将失败。当它失败时,json_decode 返回 null 或 false,所以你必须检查响应是否有效:

$chats1 = json_decode($output1, true);
$chats2 = json_decode($output2, true);

if ($chats1 && $chats2 && is_array($chats1) && is_array($chats2)) {
    // your code goes here
}

【讨论】:

  • 这并不完全正确,如果 json 仅包含双引号字符串(有效 json),这仍然会失败。
  • 添加了 is_array 检查
  • 那么问题出在其他地方?
猜你喜欢
  • 1970-01-01
  • 2013-01-08
  • 2018-10-05
  • 1970-01-01
  • 2021-01-10
  • 1970-01-01
  • 1970-01-01
  • 2013-04-21
  • 1970-01-01
相关资源
最近更新 更多