您可以幫我解釋一下這裏發生了什麼。PHP JSON編碼在未設置時將鍵轉爲字符串
$data[0] = array("one" => "uno", "two" => "dos", "three" => "tres");
$data[1] = array("one" => "uno", "two" => "dos", "three" => "tres");
//unset($data[0]);
$encode = json_encode($data);
$decode = json_decode($encode);
var_dump($decode);
輸出:
array(2) { [0]=> object(stdClass)#1 (3) { ["one"]=> string(3) "uno" ["two"]=> string(3) "dos" ["three"]=> string(4) "tres" } [1]=> object(stdClass)#2 (3) { ["one"]=> string(3) "uno" ["two"]=> string(3) "dos" ["three"]=> string(4) "tres" } }
這是正常保持它作爲數組,但只要我取消它把它變成一個obj中的陣列的一部分。
$data[0] = array("one" => "uno", "two" => "dos", "three" => "tres");
$data[1] = array("one" => "uno", "two" => "dos", "three" => "tres");
unset($data[0]);
$encode = json_encode($data);
$decode = json_decode($encode);
var_dump($decode);
輸出:
object(stdClass)#1 (1) { ["1"]=> object(stdClass)#2 (3) { ["one"]=> string(3) "uno" ["two"]=> string(3) "dos" ["three"]=> string(4) "tres" } }
如何保持一致性?
JS是一種愚蠢的,並期望所有陣列都是基於0的連續數字鍵。如果你在任何地方跳過一個鍵(例如'1,2,4,5'),或者開始非零,你會得到一個對象。 –