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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

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)?
Thats the thing... Its for a d3 visualization. Each nest will mean something different. stackoverflow.com/questions/19317115/… 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) }.
that's not a valid javascript structure. Also note that it isn't what you asked in question either
I thought so. Ill see if I can concat the values as a string or something. Thanks for the help.
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.

2 Comments

Array of class instances? stackoverflow.com/questions/8612190/array-of-php-objects Something like this?
@noc_coder like this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.