Rosamunda Rosamunda - 1 year ago 78
JSON Question

How to better format the JSON string generator with PHP json_encode()?

I'm saving data inside arrays with php's

function and then encoding them into json strings in order to save them into a single database field.

This is what I've been doing:

$fechaMensaje = $_POST['fechaMensaje'];
$mensaje = $_POST['mensaje'];
$estadoMensaje = 'abierto';
$data['fecha'][] = $fechaMensaje;
$data['autor'][] = $userEmail;
$data['mensaje'][] = $mensaje;
$datosMensaje = json_encode($data);

This does work, and it does creates a string like this:

"fecha":["29-09-2016 11:12:51 AM"],
"mensaje":["lorem ipsum"]

This is the array I've got when decoding the string:

["fecha"]=> array(1) {
[0]=> string(22) "29-09-2016 11:12:51 AM"
["autor"]=> array(1) {
[0]=> string(23) ""
["mensaje"]=> array(1) {
[0]=> string(11) "lorem ipsum"

Now, my question is, how may I change the way I'm generating the array in the first place, to get this output instead? (having the three items in the same array, so when I do add more elements it's going to be more organized).

["0"]=> array(3) {
['fecha']=> string(22) "29-09-2016 11:12:51 AM"
['autor']=> string(23) ""
['mensaje']=> string(11) "lorem ipsum"
[1]=> array(3) {

Answer Source

you can try this code dude!

$obj['fecha'] = $fechaMensaje;
$obj['autor'] = $userEmail;
$obj['mensaje'] = $mensaje;

//insert obj to data array
$data[] = $obj;

// encoding to json 
$json = json_encode($data);

hope it helps dude!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download