0

I have the following string that corresponds to a JSON object.

$string = '{"status": "success", "count": 3, "data": [{"id": 112233}]}'

And I would like to cast it to a stdClass. My current solution:

$object = (object)(array)json_decode($string);

While this is functioning, is there a better way? This seems messy and inefficient.

Seanny123
  • 8,776
  • 13
  • 68
  • 124
Anatilij K
  • 3
  • 1
  • 4

2 Answers2

2

This works, creating the associate array and passing true to json_decode:

$string = '{"status": "success", "count": 3, "data": [{"id": 112233}]}';
$object = (object)json_decode($string, true);
var_dump($object);

object(stdClass)#1 (3) { ["status"]=> string(7) "success" ["count"]=> int(3) ["data"]=> array(1) { [0]=> array(1) { ["id"]=> int(112233) } } }

Barry
  • 3,303
  • 7
  • 23
  • 42
1

A much cleaner way would be:

$string = '{"status": "success", "count": 3, "data": [{"id": 112233}]}';

$object = json_decode($string);

check out what the output for print_r($object); looks like:

stdClass Object
(
    [status] => success
    [count] => 3
    [data] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 112233
                )

        )
Javier Larroulet
  • 3,047
  • 3
  • 13
  • 30