2016-09-25 31 views
-2

我試圖添加簡單的JSON下面我陣列我的API添加JSON到數組又不丟失格式

$result = array(); 
... 
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); 
$json = json_encode($arr);    
$result['json'] = $json; 

return $result; 

但之後將其添加到我的陣列,它失去這樣的格式。

請看紅色箭頭指向與截圖比較2.

enter image description here
我要的是我的JSON應該顯示像

enter image description here

我怎麼能阻止它。任何幫助或建議將不勝感激

+0

你期待它是什麼?你已經使用了一個* associative *數組並將其轉換爲JSON字符串(它使用JSON術語定義了一個「對象」,因爲它是一個關聯數組,而不是數字索引數組),然後將該字符串添加到您的結果中。 –

+0

@ T.J.Crowder我已更新我的問題。請幫助我,我很新的PHP,我已經搜索,但仍然沒有找到答案 –

+0

兩個屏幕截圖顯示等效的JSON字符串。問題是什麼?當然,你不會佔用白空間嗎?並且雙引號在第一個截圖中被轉義,這是正常的,因爲整個字符串用雙引號引起來,它必須是這樣的,但字符串本身不存儲*反斜槓......它只是符號。 – trincot

回答

2

這裏似乎發生了什麼是雙重編碼,你的$結果數組也被編碼,然後它再次編碼$ result ['json'],導致你看到的輸出。

$result = array(); 
... 
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); 
$json = json_encode($arr);    
$result['json'] = $json; 

return $result; // either you are using a framework, or not showing a step, but this also seems to be encoded before being sent back to the client. 

鑑於我可以推斷你再告訴我們,它分配給$結果[「JSON」]之前不編碼的陣列

$result = array(); 
...   
$result['json'] = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); 

return $result; 

那麼應該給你你想要的東西。

+0

這個問題仍然很不清楚,但這也是我能做的最接近的解釋。 –

+0

最新的編輯證實了它,很好地完成。 –

0
$result = array(); 
$result['json']= array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); 
$json = json_encode($result);    

return $json; 

此解決方案正在爲我工​​作。