0

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

1
  • 2
    why are you concatenating $layout_array? Commented Oct 15, 2012 at 14:11

2 Answers 2

2

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

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

Comments

0

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.

3 Comments

I'm fully aware it's PHP! You use .= with strings, += with numbers and arrays.
@sircapsalot: .= is for concatenating. += is for adding. Both are valid PHP operators. But I don't think I've ever seen either used for adding new elements to an array.
To be honest this answer will not as expected. It's fully valid PHP but to add a new element to an array it will not work. I was thinking of the array() + array() syntax.

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.