2015-12-17 71 views
1

有一個通過REST JSON發送的curl POST請求示例。Php Json數據格式

{"email": "[email protected]", "items": [{ "name": "api Name", "quantity": 10, "unit_price": 2}, { "name": "api 2", "quantity": "4", "unit_price": 3 }] 

} 

我該如何在PHP中對其進行格式化。

我曾嘗試以下:

$data = array(
     'email' => '[email protected]', 
     ); 
$data['items'] = array(
     'name' => 'fruits', 'quantity' => 4, 
     'unit_price' => 7, 
     ); 

服務剛剛接受email,而忽略items

+0

該示例在'items'數組中包含兩個對象,您的結構包含三個標量值。 – arkascha

回答

0

items數組是一個對象數組。你是顯示字符串

+0

顯示如何正確執行此操作。 – Barmar

0

一個簡單的技巧是使用PHP函數json_decode()得到一個PHP數據結構,當傳遞給json_encode()產生你需要的字符串的地圖:

var_export(json_decode(
    '{"email": "[email protected]", "items": [{ "name": "api Name", "quantity": 10, "unit_price": 2}, { "name": "api 2", "quantity": "4", "unit_price": 3 }]}', 
    TRUE 
)); 

生產:

array(
    'email' => '[email protected]', 
    'items' => array(
     0 => array(
      'name' => 'api Name', 
      'quantity' => 10, 
      'unit_price' => 2, 
     ), 
     1 => array(
      'name' => 'api 2', 
      'quantity' => '4', 
      'unit_price' => 3, 
     ), 
    ), 
) 

通過TRUE作爲返回數組的第二個參數;沒有它,json_decode()會生成對象而不是關聯數組。

使用函數var_export()獲取生成將其作爲參數傳遞給它的數據結構的PHP代碼。

在單獨的腳本中使用上面的代碼來獲取有關您需要創建的數據結構的提示,以便在將其編碼爲JSON時獲取所需的字符串。不要把它放到你開發的產品中。

+0

我試過了,不起作用。 – bobsr