3

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).

2
  • try $this->_helper->json((object)array(0 => "value 0", 1 => "value 1")); Commented Sep 12, 2012 at 14:59
  • Thanks. However, it works for simple objects, but not in the case of nested objects. Commented Sep 13, 2012 at 7:27

1 Answer 1

2

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"]"
Sign up to request clarification or add additional context in comments.

1 Comment

Ok, it works! I've been stuck on Zend... But native php seems to be doing the job ^^. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.