Home > Blockchain >  PHP array/object definition to get JSON objects
PHP array/object definition to get JSON objects

Time:01-07

How would one go about creating array of objects in PHP that looks like this:

[{"interior_color":"white"},{"exterior_color":"black"}]

I tried it this way:

$object[] = (object) array('interior_color' => 'white', 'exterior_color' => 'black');

But I get something like this ['interior_color': 'white', 'exterior_color': 'black'] values.

CodePudding user response:

It looks like you want to create some JSON?

This will work to get the necessary structure. No need to cast anything to an object:

$data = array(
    array('interior_color' => 'white'), 
    array('exterior_color' => 'black')
);
echo json_encode($data);

Live demo: http://sandbox.onlinephpfunctions.com/code/d9eaa007985f0f7a4dbcbc17b29afa7ca60702d2


If you actually want PHP objects though (rather than the JSON representation you showed) then it's pretty similar, just add the casting and don't JSON-encode the result - but as above, you need separate objects for each colour entry:

$data = array(
    (object) array('interior_color' => 'white'), 
    (object) array('exterior_color' => 'black')
);

var_dump($data);

Live demo: http://sandbox.onlinephpfunctions.com/code/dff5f0058d3f669f66a4cdb0d7348c4218df8b6b

  •  Tags:  
  • Related