2017-01-29 71 views
1

這裏是我的代碼:如何將嵌套數組樹嵌入對象樹中?

$adjacencies = array ( "0" => array( "name1" => "pear", 
             "name2" => "jack", 
             "data" => array() ), 
         "1" => array( "name1" => "pear", 
             "name2" => "john", 
             "data" => array() ) 
        ); 

$final_array['adjacencies'] = $adjacencies; 
echo "<pre>"; 
print_r(json_encode($final_array)); 

這是上面的代碼的結果:

enter image description here

正如你看到的data的價值是[],而我想這{}代替。我怎樣才能做到這一點?

+0

的可能的複製(http://stackoverflow.com/questions/8595627/best創建一個空的對象在JSON與PHP) – Clive

回答

2

雖然我不知道什麼是你的問題背後的原因, 而不是設置data鍵作爲數組,只需將其定義爲新對象

$adjacencies = array ( "0" => array( "name1" => "pear", 
             "name2" => "jack", 
             "data" => new stdClass() ), 
         "1" => array( "name1" => "pear", 
             "name2" => "john", 
             "data" => new stdClass() ) 
        ); 

$final_array['adjacencies'] = $adjacencies; 
echo "<pre>"; 
print_r(json_encode($final_array)); 

來源:?創造JSON一個空對象與PHP的最佳方式]

http://php.net/manual/en/language.types.object.php#107071

+0

謝謝upvote – stack

1

如果它適合你(或stdClass),你可以使用ArrayObject。

PHP Manual for ArrayObject

例如:

php > echo json_encode([[],[]]); 
[[],[]] 
php > echo json_encode([ new ArrayObject(), new ArrayObject()]); 
[{},{}] 
+1

謝謝upvote – stack