2017-07-24 38 views
0

一個HTTP POST在C#中的PHP之後我在代碼中獲取形式 的輸出,我有腓解序列化一個序列化JSON字符串

public function actionSubmitInspection(){ 
     $data = $_POST; 

     return (array)$data["check_comments"]; 

    } 

現在正在逐漸形式的結果

[ 
"[{\"id\":26,\"comment\":\"89oiu\"},{\"id\":27,\"comment\":\"comment 2\"}]" 
] 

從我嘗試類型轉換數組不創建數組,我怎樣才能將序列化的字符串轉換爲數組或對象。

+0

http://php.net/manual/en/function.json-decode.php –

+2

你試過'json_decode($ result [0]);'? –

回答

1

使用json_decode函數。

public function actionSubmitInspection(){ 
     $data = $_POST; 
     // replace it 
     //return (array)$data["check_comments"]; 
     return json_decode($data["check_comments"]); 

    } 

輸出將是對象的數組。

Array 
(
    [0] => stdClass Object 
     (
      [id] => 26 
      [comment] => 89oiu 
     ) 

    [1] => stdClass Object 
     (
      [id] => 27 
      [comment] => comment 2 
     ) 

) 
1

從我嘗試類型轉換陣列犯規創建陣列

是,它創建了一個數組,但它會創建陣列包含JSON文本。

您需要解析JSON以恢復其編碼的數據結構。 PHP爲此提供了功能json_decode()。我建議你通過TRUE作爲json_decode()的第二個參數來取回數組(否則它會創建stdClass對象,這些對象只是具有花哨語法和處理有限選項的數組)。

// Assuming the value of $data['check_comments'] is: 
// "[{\"id\":26,\"comment\":\"89oiu\"},{\"id\":27,\"comment\":\"comment 2\"}]" 
$output = json_decode($data['check_comments']); 

print_r($output); 

輸出:

Array 
(
    [0] => Array 
     (
      [id] => 26 
      [comment] => 89oiu 
     ) 
    [1] => Array 
     (
      [id] => 27 
      [comment] => comment 2 
     ) 
) 
1

應使用json_decode($data["check_comments"])的輸出將是一個陣列stdClass的的對象

Array 
(
    [0] => stdClass Object 
     (
      [id] => 26 
      [comment] => 89oiu 
     ) 

    [1] => stdClass Object 
     (
      [id] => 27 
      [comment] => comment 2 
     ) 

) 

或第二PARAM傳遞truejson_decode($data["check_comments"], true)和輸出將是一個陣列陣列

Array 
(
    [0] => Array 
     (
      [id] => 26 
      [comment] => 89oiu 
     ) 

    [1] => Array 
     (
      [id] => 27 
      [comment] => comment 2 
     ) 

)