2016-09-29 23 views
1

我使用php的json_encode()函數將數據保存在數組中,然後將它們編碼爲json字符串,以便將它們保存到單個數據庫字段中。如何更好地使用PHP json_encode()格式化JSON字符串生成器?

這是我一直在做:

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

這並不工作,它並創建一個像這樣的字符串:

{ 
"fecha":["29-09-2016 11:12:51 AM"], 
"autor":["[email protected]"], 
"mensaje":["lorem ipsum"] 
} 

這是我數組解碼字符串時得到:

{ 
    ["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" 
    } 
} 

現在,我的問題是,我該如何改變我在第一個地方生成數組的方式,以獲得此輸出呢? (在同一個數組中有三個元素,所以當我添加更多元素時,它將更加有組織)。

{ 
    ["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) { 
     ... 
     ... 
     ...  
    } 
} 
+0

'$數據[ '出生日期'] []'你不想說'[]'在結束 - 這是分配數據作爲數組不是一個佔據不同結構的字符串。 – CD001

+0

'data [] ['fecha'] = $ fechaMensaje;''等等如何? – Hackerman

回答

3

你可以試試這個代碼:

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

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

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

可以定義另一個數組,在下面的情況下$some_var,包含數據的每個陣列。在分配$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);