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条)

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line