简体   繁体   中英

How to create this array structure in PHP

I am trying to create an array structure like the initial one found here: D3 JSON data conversion

Mine would look something like the below, be dynamic, and then be passed to json_encode() to make a json object.

[
  { "name": "Table1", "lab": "name1", "cell": "c1", "avg": avgUsage1},
  { "name": "Table1", "lab": "name2", "cell": "c2", "avg": avgUsage2},
  { "name": "Table1", "lab": "name3", "cell": "c3", "avg": avgUsage3},
  { "name": "Table1", "lab": "name4", "cell": "c4", "avg": avgUsage4},
  { "name": "Table1", "lab": "name5", "cell": "c5", "avg": avgUsage5} ...
]

The problem is that I cannot have an array that has the same values for the key. What is this data structure and how can I create something like it to then create a nested structure (I will follow the linked post to create the nested structure)?

Not sure why you think there would be same keys. You would have a multidimensional array in php that would look like:

$arr = array(
    array( "name"=> "Table1", "lab"=> "name1", "cell"=> "c1", "avg"=>$avgUsage1),
    array( "name"=> "Table2", "lab"=> "name2", "cell"=> "c2", "avg"=>$avgUsage2),
    //....
);

or each element could also be a stdClass object

You can initialize it like that:

$arrayJSON = array(
    array(
        "name" => "Table1",
        "lab" => "name1",
        "cell" => "c1",
        "avg" => "avgUsage1"
    ),
    array(
    ....
    )
);

You can also make an array of class instances.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM