2011-03-06 55 views
7

如何從json_decode()獲取數組?從json_decode獲取數組結果

我有一個這樣的數組:

$array = array(
    'mod_status' => 'yes', 
    'mod_newsnum' => 5 
); 

,我保存在這個數據庫中像JSON編碼:

{"mod_status":"yes","mod_newsnum":5} 

現在我想從數據庫中再得到陣列。但是當我使用:

$decode = json_decode($dbresult); 

我得到:

stdClass Object (
    [mod_status] => yes 
    [mod_newsnum] => 5 
) 

不是數組的。我怎樣才能得到一個數組而不是一個對象?

回答

21

設置的json_decode爲true的第二個參數來強制關聯數組:

$decode = json_decode($dbresult, true); 
+0

這應該是真正的答案,對我更有幫助。 – Stefan

7

http://in3.php.net/json_decode

$decode = json_decode($dbresult, TRUE); 
+1

1對於使用的縮寫「讀** **細手冊」。 ;) – Gumbo

+0

F是爲了嚇倒「F」字:P – Kumar

+0

[很好](http://stackoverflow.com/faq#benice)。 – 2011-03-06 07:55:45

0

如果你只在PHP中使用這些數據,我建議使用serializeunserialize代替,否則你將永遠無法對象和關聯數組之間進行區分,因爲對象類編碼爲JSON時信息丟失。

<?php 
class myClass{// this information will be lost when JSON encoding // 
    public function myMethod(){ 
     echo 'Hello there!'; 
    } 
} 
$x = array('a'=>1, 'b'=>2); 
$y = new myClass; 
$y->a = 1; 
$y->b = 2; 
echo json_encode($x), "\n", json_encode($y); // identical 
echo "\n", serialize($x), "\n", serialize($y); // not identical 
?> 

Run it.

+0

不回答問題:。應改爲評 – 2011-03-06 07:51:58

+1

@馬克它提出,可能是更好的替代我認爲這些種有效的答案,以及我加了一些更多的參數。在最新的編輯 –

2
$decode = json_decode($dbresult, true); 

或者

$decode = (array)json_decode($dbresult); 
0

鑄造OBJE對數組的json_decode的ct結果可能會有意想不到的結果(並導致頭痛)。因此,建議使用json_decode($json, true)而不是(array)json_decode($json)。下面是一個例子:

斷裂:

<?php 

$json = '{"14":"29","15":"30"}'; 
$data = json_decode($json); 
$data = (array)$data; 

// Array ([14] => 29 [15] => 30) 
print_r($data); 

// Array ([0] => 14 [1] => 15) 
print_r(array_keys($data)); 

// all of these fail 
echo $data["14"]; 
echo $data[14]; 
echo $data['14']; 

// this also fails 
foreach(array_keys($data) as $key) { 
    echo $data[$key]; 
} 

工作:

<?php 

$json = '{"14":"29","15":"30"}'; 
$data = json_decode($json, true); 

// Array ([14] => 29 [15] => 30) 
print_r($data); 

// Array ([0] => 14 [1] => 15) 
print_r(array_keys($data)); 

// all of these work 
echo $data["14"]; 
echo $data[14]; 
echo $data['14']; 

// this also works 
foreach(array_keys($data) as $key) { 
    echo $data[$key]; 
}