daniel__
daniel__

Reputation: 11845

json_decode to array, not working

i have this variable $a

var_dump($a)

 array(3) { [0]=> string(10) "designer" [1]=> string(8) "director" [2]=> string(10) "Freelancer"} 

i am sending this in ajax(jquery)

jquery

  data: 'form=<?php echo json_encode($a); ?>',

and in the other php file i am doing

$send = $_POST[form];

$b = json_encode($send);

$c = json_decode($b, true);
var_dump($c);

the output will be:

string(xx) "[\"designer\",\"director\",\"Freelancer\"]" 

but, echo $c[0] show this: [ and should be "designer"

Any help ?

EDIT: already tried too

$send = $_POST['form'];

$c = json_decode($send, true);

var_dump($c);

output: `null`

Upvotes: 1

Views: 5419

Answers (2)

deceze
deceze

Reputation: 522109

$_POST[form] already is a JSON encoded string. If you encode it again, then decode it, you'll end up with the same string, not an array. You don't need $b = json_encode($send).

It also looks like you have Magic Quotes on. Turn them off or follow the documentation to clean your strings: http://www.php.net/magic_quotes

Also, quote your array indices!

$send = $_POST['form'];

http://www.php.net/manual/en/language.types.array.php#language.types.array.donts

Upvotes: 0

Jon Newmuis
Jon Newmuis

Reputation: 26502

Because $c is actually the string "[\"designer\",\"director\",\"Freelancer\"]", and not the array ["designer", "director", "Freelancer"]. It looks like you're calling json_encode on your content twice, and json_decode once.

  1. form=<?php echo json_encode($a); ?> will encode your content once, before sending it over the wire.
  2. $send = $_POST[form]; will get that content (already json_encoded).
  3. $b = json_encode($send); will encode that same content a second time.
  4. $c = json_decode($b, true); will decode it.

This will leave you with your content still encoded. I'm not quite sure what the point of step 3 is, and it looks to me that removing it should solve your problem.

EDIT:

Since you've updated the question stating that you get null if you try the proposed solution, according to the PHP documentation for json_decode:

NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.

You should make sure that the data is set to exactly what you want, as I don't think your recursion level is too deep in this case (from the data you've given, it appears as if there is none whatsoever).

Upvotes: 2

Related Questions