Can you guys help me explain what is happening here.
$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);
outputs:
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" } }
This is normal keeps it as an array but as soon as I unset a part of the array it turns it into an 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);
output:
object(stdClass)#1 (1) { ["1"]=> object(stdClass)#2 (3) { ["one"]=> string(3) "uno" ["two"]=> string(3) "dos" ["three"]=> string(4) "tres" } }
How do I keep the consistency?
I would look at json_encode at the options. I think JSON_FORCE_OBJECT should force constancy.
As Marc B explained in a comment, you need to re-index the array to zero-based indexes. In PHP that can be done with array_values:
$encode = json_encode(array_values($data));
See as well:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With