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

foreach ($object_ids as $value) {
    $booking_data = array(
        'name' => $name, 
        'phone' => $phone, 
        'email' => $email,
    );
}
$booking_data = json_encode($booking_data,true);
print_r($booking_data);

and then is the result I got

{"name":"Peter ","phone":"03008000000","email":"peter@gmail.com"}{"name":"Jessica ","phone":"03038518000","email":"jesica@gmail.com"}{"name":"Anas ","phone":"03234152099","email":"anasiqbal1992@gmail.com"}{"name":"Anas ","phone":"03234152099","email":"anasiqbal1992@gmail.com"}

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…

$booking_data = array(
  'name' => $name, 
  'phone' => $phone, 
  'email' => $email,
);

… 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:

print_r($booking_data)

… 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:

foreach ($object_ids as $value) {
    $booking_data[] = array(
        'name' => $name, 
        'phone' => $phone, 
        'email' => $email,
    );
}
echo json_encode($booking_data);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement