Skip to content
Advertisement

Error in json data using php json_encode for php array

I am saving data in php array in loop and then use json_encode function. Here is my code

JavaScript

and then is the result I got

JavaScript

When I tried to beautify I get this error:

The comma is missing while encoding. Please let me know my mistake.

Regards

Advertisement

Answer

It’s not really clear what you’re doing here. First, this part…

JavaScript

… will rewrite the value of the same variable again and again – without actually encoding it (which happens outside of loop). As you’re clearly getting some output, this looks more of a typo when trying to create a sample to post in SO though.

Second, this part:

JavaScript

… makes little sense, as result of json_encode is string, not an array.


What seems to happen there (according to the output you’ve shown) is that you actually add into some array results of json_encoding each individual associative array (with name, phone and email keys), then attempt to work with print_r() representation of that “array of JSONs”. But that’s not right: array of JSONs printed out with print_r doesn’t give out a JSON!

Instead of doing all this, why don’t you just create an array of arrays, then json_encode it once? Like this:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement