开发者

What exactly is this structure

开发者 https://www.devze.com 2023-02-23 22:55 出处:网络
Is this an object that contains objects or an array of objects? var rgb = { ball: { Red: 232, Green: 23, Blue: 23},

Is this an object that contains objects or an array of objects?

var rgb = {
  ball: { Red: 232, Green: 23, Blue: 23},
  square: { Red: 42, Green: 83, Blue: 32},
};

I need to generate it with php and then dec开发者_运维知识库lare it in my script, so want to know what I should be building in php


This is an object, which contains two properties : ball and square.

Each one of these properties is an object, containing three properties (Red, Green, and Blue) -- which are numbers.


In Javascript :

  • {} mean object : {item1: 'value1', item2: 123}
  • and [] mean array : [1, 2, 3, 4]


From PHP, you can build the equivalent data-structure using something like this :

$data = (object)array(
    'ball' => (object)array('Red' => 232, 'Green' => 23, 'Blue' => 23), 
    'square' => (object)array('Red' => 42, 'Green' => 83, 'Blue' => 32), 
);

And, then, convert it to JSON with the json_encode() function :

$json = json_encode($data);
echo $json;


It is a Javascript object that contains other objects.

You should be able to generate it in PHP using json_encode() and the JSON_FORCE_OBJECT parameter like so:

$rgb = new STDClass();
$rgb->ball = new STDCLass();
$rgb->square = new STDCLass();
$rgb->ball->Red = 232;
$rgb->ball->Green = 23;

// .... and so on

echo json_encode($rgb, JSON_FORCE_OBJECT);


It is an object with two properties, ball and square which are objects themselves. Both of them have the properties Red, Green and Blue


$array = array('ball'=>array('Red'=>232));
var_dump(json_encode($array));

This is only the short version. You should be able to add the other keys by yourself.

Because Javascript dont know associative arrays its not required to use objects here, because it will result into the same JSON-encoded string.

0

精彩评论

暂无评论...
验证码 换一张
取 消