2017-06-20 28 views
0

我有一個數組寫入和讀取與指定數組中的鍵爲JSON文件

$monthlyStatistics = array('total' => 1, 'opened' => 1, 'clicked' => 1, 'bounced' => 1, 'optout' => 1); 

,我已經保存到一個JSON文件

$monthlypath = '/storage/monthlytotals.json'; 
file_put_contents($monthlypath, json_encode($monthlyStatistics)); 

,我需要閱讀該JSON文件和使用指定的鍵將內容作爲數組輸出。我目前做這個:

$monthlypath = '/storage/monthlytotals.json'; 
$read_file = file_get_contents($monthlypath); 
$monthlytotals = json_decode($read_file); 

我知道file_put_contents把爲一個字符串,該文件()應該將整個文件讀入一個數組(我目前沒有使用,因爲它不讀什麼file_put_contents寫道)。

我在做這個錯誤還是我錯過了一個函數,應該與file()一起寫入數組?

+0

你看了['json_decode()'](http://php.net/manual/en/function.json-decode.php)的文檔嗎? – axiac

+0

是的我已閱讀文檔 – Cyberio

回答

1

您試圖從內存中的PHP數據結構轉換爲可寫入磁盤的內容。不知何故,需要串行化 - 通過json_encode()serialize()

file()讀取文件到行列表(每行數組一行)。

對於你在做什麼,

file_put_contents($monthlypath, json_encode($totals))

$totals = json_decode(file_get_contents($monthlypath), true)

可能是所有你可能需要。

+0

謝謝!我會盡力回覆你。那個建議的方法會保留指定的鍵值嗎? – Cyberio

+0

是的。兩者都會。 'serialize'將處理更多的php數據類型(特別是對象),而'json_encode'可能更安全。 –