2014-10-10 40 views
-1

我正嘗試使用PHP作爲命令行腳本。我傳遞一個json字符串給它,並且我正在嘗試讀取這些值,但是當我執行echo $user_inputs["foo"];時出錯,這是爲什麼?我忘了關於json_decode的一些事情,還是關於使用STDIN?迴應給予PHP腳本的STDIN

my_test.php

// Get the STDIN. 
$stdin = fopen('php://stdin', 'r'); 

// Initialize user_inputs_json which will be the entire stdin. 
$user_inputs_json = ""; 

// Read all of stdin. 
while($line = fgets($stdin)) { 
    $user_inputs_json .= $line; 
} 

// Create the decoded json object. 
$user_inputs = json_decode($user_inputs_json); 

// Try to echo a value. This is where I get my error (written out below). 
echo $user_inputs["foo"]; 

fclose($stdin); 

運行此命令行通過JSON到它:

$ echo '{"foo":"hello world!", "bar": "goodnight moon!"}' | php my_test.php

我得到這個錯誤:

Fatal error: Cannot use object of type stdClass as array in /Users/don/Desktop/my_test.php on line 20

+1

'$ user_inputs-> foo'應該在這種情況下做到這一點。沒有? – Ohgodwhy 2014-10-10 21:32:32

回答

1

默認情況下,json_decode將JSON字符串轉換爲PHP對象。如果你想獲得PHP陣列,使用json_decode的第二個參數:

$user_inputs_array = json_decode($user_inputs_json, true); 
0

如果你需要經常處理的JSON傳遞作爲數組,將第二json_decode參數設置爲true,迫使它解碼作爲array:

$user_inputs = json_decode($user_inputs_json, 1);