Colin
Colin

Reputation: 434

PHP- confirmed I am using an array, but still getting Invalid argument supplied for 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?

Upvotes: 0

Views: 57

Answers (2)

Gergo Erdosi
Gergo Erdosi

Reputation: 42048

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

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

Upvotes: 2

Marc B
Marc B

Reputation: 360682

$brands is an array, but $brands['brand_name'] isn't, and that's what you're looping on. e.g.

$foo = array('bar' => 'baz');
^^^^--array  ^^^^^-key ^^^^---string

foreach($foo as $value) { }  // this is ok. $foo is an array
foreach($foo['bar'] as $value) { } // this is wrong. $foo['bar'] is a STRING

Upvotes: 2

Related Questions