ajl80
ajl80

Reputation: 43

json generating array problems

I want to generate a json array and store it in my db. I get the values and run a loop to generate.

when I encode it I'm getting ArrayArrayArray

Can anyone see where I'm going wrong

for ($i=0; $i<=$sTotal;$i++){ 
    $layout_array .= array(array("cellID" => '"'. $_POST['cell_'.$i] .'"',"studentID" => $_POST['user_'.$i]),);
}
$layout_array .= array(array("cellID" => "null","studentID" => "null"));
$layout = json_encode($layout_array);
echo $layout;

Cheers

Upvotes: 0

Views: 75

Answers (2)

Ofir Baruch
Ofir Baruch

Reputation: 10346

The problem is that your $layout_array is a String , because you're using .= (concatenating).

Instead of:

$layout_array .= array(array("cellID" => '"'. $_POST['ce...

Do:

$layout_array[] = array(array("cellID" => '"'. $_POST['ce....

And change the next line as well:

$layout_array .= array(array("cellID" => "null","studentID" => "null"));

BTW , why not using serialize and unserialize instead of json encoding?

EDIT: For your comfort , links to the php manual of the functions I've suggested.

http://php.net/manual/en/function.serialize.php

http://php.net/manual/en/function.unserialize.php

Upvotes: 2

Matt Humphrey
Matt Humphrey

Reputation: 1554

You should be using += to join your arrays, not ..

Edit: Ignore this and see comments. This will add elements to the current scope of the array, you should be using $array[] = array(..) as the other answer states.

Upvotes: 0

Related Questions