-1

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)?

Community
  • 1
  • 1
noc_coder
  • 349
  • 1
  • 15

2 Answers2

3

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

charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • Is it possible to add multiple mysql table values in the "avg" field to be displayed along with the avg? Something like: Value1, Value2..... AVG(Values)? – noc_coder Sep 25 '16 at 23:51
  • Thats the thing... Its for a d3 visualization. Each nest will mean something different. http://stackoverflow.com/questions/19317115/convert-flat-json-file-to-hierarchical-json-data-like-flare-json-d3-example-fil So instead of this: { "dep": "First Top", "name": "First child", "model": "value1", "size": "320" }, I am looking for this: {"lab": "labname", "cell", "cell_name", "usage": Week1, Week2, Week3, Week4, Week5, Avg( Week1 + Week2 + Week3 + Week4 + Week5) }. – noc_coder Sep 25 '16 at 23:58
  • that's not a valid javascript structure. Also note that it isn't what you asked in question either – charlietfl Sep 26 '16 at 00:00
  • I thought so. Ill see if I can concat the values as a string or something. Thanks for the help. – noc_coder Sep 26 '16 at 00:02
1

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.

Dominique Lorre
  • 1,168
  • 1
  • 10
  • 19