Rosamunda
Rosamunda

Reputation: 14980

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

I'm saving data inside arrays with php's json_encode() 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"],
"autor":["[email protected]"],
"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) "[email protected]" 
    } 
    ["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) "[email protected]" 
        ['mensaje']=> string(11) "lorem ipsum" 
    } 
    [1]=> array(3) { 
        ...
        ...
        ...       
    } 
}   

Upvotes: 1

Views: 115

Answers (2)

Jacob Paulozz
Jacob Paulozz

Reputation: 159

You can try this code:

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

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

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

Upvotes: 3

Rax Weber
Rax Weber

Reputation: 3780

You can define another array, in the below case $some_var, to contain each array of data. Also remove [] on the end when assigning the values for $data.

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

Upvotes: 3

Related Questions