0

I am probably missing something simple here but I feel it best to ask anyway.

I have the following code:

$newarray = json_decode($jsoncode);
$rad = 24;
foreach ($newarray->objname as $obj)
{
    echo "<map name='" . $mapname . "'>";
    echo "<area shape=\"circle\" coords='" . $obj->x . "," . $obj->y . "," . $rad . "' alt='" . $obj . "'>";
    echo '</map>';
}

coming from a manually created json string:

$jsoncode = '{"objname":{"Forest 1":{"x":120,"y":120},"Forest 2":{"x":434,"y":225}}}';

I am getting an error when trying to call the $obj variable to use within the foreach. Is there like something I have to add to make it show the name stored in the variable?

P.S. I have no problem with the rest of the code

1
  • 1
    In the future, if you are getting any errors - you should include them in your post...
    – Lix
    Jul 16, 2012 at 23:05

1 Answer 1

2

PHP's foreach syntax should be like this -

foreach ($array AS $key=>$object){ 
  ... 
}

So your code should look like this -

foreach ($newarray AS $objectName => $obj)
  • $objectName is the index in $newarray.
  • $obj is the actual element from the array.

http://php.net/manual/en/control-structures.foreach.php

The documentation has this to say about the syntax of the foreach statement -

foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement

2
  • so are you saying foreach ($newarray->objname AS $key=>$obj){
    – Adsy2010
    Jul 16, 2012 at 23:02
  • 1
    im impressed actually! that's explained even more! Half understanding functions and knowing how they work is easily beaten by fully understanding them. Thankyou, I will accept after this time limit thing. Actually just tested it and I did need the $newarray->objname still but the rest worked fine.
    – Adsy2010
    Jul 16, 2012 at 23:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.