0

In php I have something like this:

$i=1; 
foreach ($result as $row){
    $outp['fields'][$i]['id']=$row['id'];
    $outp['fields'][$i]['x']=$row['x'];
    $outp['fields'][$i]['y']=$row['y'];
    $outp['fields'][$i]['type']=$row['type'];
    $i++;
}
echo json_encode($outp)

And in the JS:

success: function(data) {
  var map = eval('(data)');
}

And here is the JSON output:

{"fields":
     {"1":{"id":9521,"x":21,"y":96,"type":2},
      "2":{"id":9522,"x":22,"y":96,"type":3},
      "3":{"id":9523,"x":23,"y":96,"type":1},
      "4":{"id":9930,"x":30,"y":100,"type":3}
     } 
}

I want to write html code for every field (4 fields in that case). How can I do it? is this possible to convert var map into array?

Thanks

1 Answer 1

0

Try this:

for(var i=1;i<=Object.keys(map["fields"]).length;i++){
    console.log(map["fields"][i]["id"]); //id
    console.log(map["fields"][i]["x"]);  //x
    console.log(map["fields"][i]["y"]);  //y
}
4
  • excellent! but if I want to write field inside loop like this $("#map").append("<div class='mapField'></div>"); it append just 3 fields(loop goes 50x), where can be problem? Commented Mar 2, 2013 at 10:58
  • Do you mean there are 50 elements in map["fields"]? Also, I forgot to write <= in for loop and updated my solution. Commented Mar 2, 2013 at 11:05
  • Could you post your problem in jsFiddle? I tried to do what you want in jsFiddle, and it worked. Look at this: jsfiddle.net/TQuLj Commented Mar 2, 2013 at 11:10
  • hm, it really works on fiddle, but I have same code..my code goes through ajax but it can't be problem..thanks for help, I will must resolve it on my own Commented Mar 2, 2013 at 11:12

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.