dongwuwu6104 2014-07-08 21:59
浏览 113
已采纳

PHP-确认我正在使用数组,但仍然获得为foreach()提供的无效参数

Using this code:

    $brands = json_decode($data, true);

    echo json_encode($brands);
    echo "<br>";
    echo gettype($brands);
    echo "<br>";


    foreach ($brands['brand_name'] as $brand) {
        echo $brand, '<br>';
    }

I am getting a Warning: Invalid argument supplied for foreach(). If I add in these lines:

    $brands = json_decode($data, true);

    echo json_encode($brands);
    echo "<br>";
    echo gettype($brands);
    echo "<br>";


    foreach ($brands['brand_name'] as $brand) {
        echo $brand, '<br>';
    }

I can see the data that I'm working with and also confirm that $brands is an array. Here is the output on the page when viewed in a browser:

{"result":1,"results":[{"brand_id":"1","brand_name":"Gildan"},{"brand_id":"2","brand_name":"American Apparel"},{"brand_id":"3","brand_name":"Rabbit Skins"},{"brand_id":"4","brand_name":"Anvil"},{"brand_id":"5","brand_name":"Bella / Canvas"},{"brand_id":"6","brand_name":"Alternative"},{"brand_id":"8","brand_name":"Hanes"},{"brand_id":"9","brand_name":"ALO"},{"brand_id":"10","brand_name":"Augusta"},{"brand_id":"11","brand_name":"Precious Cargo"},{"brand_id":"12","brand_name":"Other"},{"brand_id":"13","brand_name":"Jerzees"},{"brand_id":"15","brand_name":"Liberty Bags"},{"brand_id":"16","brand_name":"Port Authority"},{"brand_id":"17","brand_name":"Next Level"}]} array

Warning: Invalid argument supplied for foreach() in -- on line 36

Since $brands is an array, I'd think this should work. Any ideas why it is not?

  • 写回答

2条回答 默认 最新

  • dongyan7172 2014-07-08 22:01
    关注

    You should iterate through $brands['results'] instead:

    foreach ($brands['results'] as $brand) {
        echo $brand['brand_name'], '<br>';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?