Reputation: 1870
I use zend's JSON helper, and I have a problem... When I use this code :
$this->_helper->json(array(1 => "value 1", 2 => "value 2"));
I get an object:
{1: "value 1", 2: "value 2" }
But if the keys are a sequence beginning by "0", I get an array. For exemple, with :
$this->_helper->json(array(0 => "value 0", 1 => "value 1"));
I get an array:
["value 0", "value 1"]
How can I do to get an object every time I use this method ? (I want the result {0: "value 0", 1: "value 1" }
in the second example).
Upvotes: 3
Views: 407
Reputation: 12830
You can force it to be an object
<?php
$arr = array(1 => "value 1", 2 => "value 2");
$x = json_encode($arr);
var_dump($x);
//use this to force to be an object
$y = json_encode(array(0 => "value 1", 1 => "value 2"), JSON_FORCE_OBJECT);
var_dump($y);
// how it is
$z = json_encode(array(0 => "value1", 1 => "value 2" ));
var_dump($z);
?>
gives
string(29) "{"1":"value 1","2":"value 2"}"
string(29) "{"0":"value 1","1":"value 2"}"
string(20) "["value1","value 2"]"
Upvotes: 2