【问题标题】:Parameter must be an array or an object that implements Countable?参数必须是数组还是实现了Countable的对象?
【发布时间】:2019-09-21 12:00:16
【问题描述】:

我有这个返回错误的代码:

$response = curl_exec($client);

$result = json_decode($response);

$output = '';

if(count($result) > 0)

{

foreach($result as $row)

{

$output .= '

<tr>

<td>'.$row->name.'</td>

<td>'.$row->url.'</td>

错误

参数必须是数组还是实现了Countable的对象?

【问题讨论】:

    标签: php json ajax


    【解决方案1】:

    您的代码首先有一些语法错误,您可以在此之前解决它。我猜你 $result 可能是一个数组。然后,您可以在 if 中添加 is_array 来为您检查。

    $response = curl_exec($client);
    $result = json_decode($response, true);
    $output = '';
    
    if (count($result) > 0 && is_array($result)) {
        foreach ($result as $row) {
            $output .= '<tr><td>' . $row->name . '</td><td>' . $row->url . '</td></tr>';
        }
    }else{
        die("Sorry! Result is not an array!");
    }
    

    这也是一个常见的错误。您可能会查看一些类似的帖子,例如 this post,其中解释了该错误。

    【讨论】:

    • 您能解释一下您对 OP 代码的改进吗,Emma?您如何验证代码不再抛出与问题中相同的错误?
    猜你喜欢
    • 2018-11-18
    • 2019-10-18
    • 2019-10-04
    • 2019-07-23
    • 2018-06-28
    • 2018-09-05
    • 2019-08-03
    • 2019-06-02
    相关资源
    最近更新 更多