Reputation: 570
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":"[email protected]"}{"name":"Jessica ","phone":"03038518000","email":"[email protected]"}{"name":"Anas ","phone":"03234152099","email":"[email protected]"}{"name":"Anas ","phone":"03234152099","email":"[email protected]"}
When I tried to beautify I get this error:
The comma is missing while encoding. Please let me know my mistake.
Regards
Upvotes: 1
Views: 947
Reputation: 106385
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);
Upvotes: 1