0

I am passing a list of numbers from a page to PHP serialized in JSON

{"items":"[1,2,3,4]"}

in my URL it is just

...&items={"items":[1,2,3,4]}

I decode this in PHP

$json = $_GET["items"];
$arr = json_decode($json, true);

I get an array

Array ( [items] => [1,2,4] )

But when I try a foreach on arr["items"] and print out each value, all I get is a single value

[1,2,4]

This is the code I am using to iterate

foreach($res["items"] as $value)
    echo $value; 

How come I am not getting something like

1
2
4
3
  • Why do you serialize them on the client? Why don't you pass array as-is? Commented Nov 27, 2012 at 21:59
  • because I have never worked with PHP. How can I pass arrays from javascript to PHP directly? Commented Nov 27, 2012 at 22:00
  • Oh, didn't know about that. Would I just iterate over $_GET["items"] to access each value? Commented Nov 27, 2012 at 22:02

2 Answers 2

5

Look closely at your json string:

{"items":"[1,2,3,4]"}

Look closer:

"[1,2,3,4]"

You are saying that items is a string containing:

"[1,2,3,4]"

Remove the " and you'll be fine.

Sign up to request clarification or add additional context in comments.

Comments

2

Your serialization is wrong. Should be:

{"items":[1,2,3]}

To get rid of problems like that use JSON.stringify in JS:

var myData = {"items" : [1,2,3]},
    queryString = 'data='+encodeURIComponent(JSON.stringify(myData));

for IE < 8 it has to be included from external script (see here) :

<!--[if lt IE 8]><script src="/js/json2.js"></script><![endif]-->

Anyway much easier would be to send it already as an array:

items[0]=1&items[1]=2&items[2]=3

This way you can send also more complex structures:

data[items][0]=1&data[items][1]=2
// on PHP side will become
$_GET['data'] = array('items' => array(1,2))

2 Comments

My data comes in JSON so I figured it would be convenient to just pass it down as JSON as well.
If you really want to send data in json then safer would be use JSON.stringify() method from JS (for IE < 8 you need to include it github.com/douglascrockford/JSON-js).

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.