11

Long story short, client's hosting is using php 5.2.5 and i desperately need to use the JSON_FORCE_OBJECT option with json_encode() that came with 5.3. Does anyone know some equivalent for that purpose? Point it out please.

2
  • 10
    @cletus if only we all had control over every hosting environment ever Commented Apr 14, 2010 at 0:08
  • ...i'm still on 4.2 /cry Commented Apr 14, 2010 at 0:16

2 Answers 2

18

Casting as an object before encoding worked for me on 5.2.5:

$array = array(1,2,3);

echo json_encode($array);
// [0,1,2]
echo json_encode((object)$array);
// {"0":1,"1":2,"2":3}

And using PHP 5.3 yields the same output:

echo json_encode($array);
// [0,1,2]
echo json_encode($array, JSON_FORCE_OBJECT);
// {"0":1,"1":2,"2":3}

You might also try this solution from another thread. Not sure what your exact use-case is.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the PHP pear package to support json_encode on older versions of PHP. It seems to support encoded objects.

Checkout http://pear.php.net/package/Services_JSON/

Comments

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.