Tristan12
Tristan12

Reputation: 35

Json array in php as a tree format

I have this php code to form the hierarchy

    $arr = array(
    'name' => "Level 2: A",
    'parent' => "Top Level",
    'children' => ""
);

$arr2 = array(
    'name' => "Top Level",
    'parent' => "null",
    'children' => "$arr"
);

echo json_encode($arr2);

But i cant access the array in the JSON output.

MY output from JSON: {"name":"Top Level","parent":"null","children":"Array"}

My goal is to create an array like this but with JSON but it returns as an array instead of the data inside the array

var treeData = [
{
"name": "Top Level",
"parent": "null",
"children": [
  {
     "name": "Level 2: A",
     "parent": "Top Level",
     "children": [
      {
        "name": "Son of A",
        "parent": "Level 2: A"
      },
      {
        "name": "Daughter of A",
        "parent": "Level 2: A"
      }
    ]
  },
  {
    "name": "Level 2: B",
    "parent": "Top Level"
  }
]

} ];

Upvotes: 1

Views: 377

Answers (1)

Jakub Matczak
Jakub Matczak

Reputation: 15656

You have to remvoe quotes abour $arr

$arr2 = array(
    'name' => "Top Level",
    'parent' => "null",
    'children' => $arr // <- remove quotes here
);

When you do "$arr", you're actually converting $arr to string. That's why you have just Array string in JSON.

Moreover I would suggest to change children property in $arr to empty array instead of empty string:

$arr = array(
    'name' => "Level 2: A",
    'parent' => "Top Level",
    'children' => array() // <- here
);

This will make your code consistent, since you will always have an array under children property.

Upvotes: 2

Related Questions