Question

I have the following JSON:

{"name":"Hello World","products":[{"name":"cup","type":"large"},{"name":"spoon","type":"small"}]}

I'm using a curl request and Slim to get:

$vars = json_decode($app->request->getBody(), true);
print_r($vars);

But it takes away the quotes for the name and type, so when I try to use a foreach loop on them, it doesn't think they are strings.

Array
(
  [name] => Hello World
  [products] => Array
    (
        [0] => Array
            (
                [name] => cup
                [type] => large
            )

        [1] => Array
            (
                [name] => spoon
                [type] => small
            )

    )

)

When I use a foreach like this:

foreach ($vars as $var){
   print_r($var);
   echo $var[0]['name'];
}

I get the error: Illegal string offset 'name' Why is this occurring? Thanks for all help!

Was it helpful?

Solution

I get the error: Illegal string offset 'name' Why is this occurring?

Because the first element you are iterating over is $vars['name'], which has the value 'Hello World', which is a string. And 'Hello World'['name'] just doesn't work.

Looks like you want to iterate over $vars['products'] only.

OTHER TIPS

You're looping the outer loop. Looks like you want to loop products only.

foreach ($vars['products'] as $var) {
   echo $var['name'];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top