0

I have to create Matrix tree view in my project. So am plan to use json. My question is how to fetch PHP values in Json ?. I did static matrix tree but i want dynamic. Thank you for advance.

My code is following:

<?php
include('db.php');
$select = mysql_query("select * from table1");
while($row = mysql_fetch_array($select))
{
?>
{
 "name": "A", // Here database values come $row['name']; 
 "children": [



  {
   "name": "B",
   "children": [
    {"name": "B-1"}
   ]
  },
  {
   "name": "C",
   "children": [
    {"name": "C-1", "size": 1082},

    {"name": "C-2", "size": 1681}
   ]
  },



  {
   "name": "D",
   "children": [
    {
     "name": "D-1",
     "children": [
      {"name": "D-1 1", "size": 1302},


      {"name": "D-1 2", "size": 6703}
     ]
    },

   {"name": "D-2", "size": 16540}
   ]
  }
 ]
}
<?php
}
?>
2
  • Dou you also get all the chilrens from the database or how will you get the mapping with children objects? Commented Apr 13, 2016 at 10:57
  • <insert obligatory dont use mysql driver its bad, dangerous and removed in php7 message here> Commented Apr 13, 2016 at 10:59

2 Answers 2

1

In this example Im using the mysqli driver. Do not use the mysql driver.

you just need to convert your output data into a json object.

Its possible to extract all the rows at once which is going to give you a marginally less overhead.

$data = mysqli_fetch_all($select); // returns everything in an associative array
$json_data = json_encode($data); // converts that array to json.

if you need specific keys, then manipulate your query to rename columns as necessary eg.

$query = "select name as firstname from ....";
Sign up to request clarification or add additional context in comments.

Comments

0

You can just retrieve data from your database and store it in arrays like you normally would. Then call PHP's built in function json_encode() to transform your PHP array into json (assuming your PHP array is well formed (which should be the case if you get it out of a database)).

You could argue that this is slower because you're iterating over the data twice instead of once, but it shouldn't matter, the complexity remains the same.

1 Comment

Ya i fefer this link Refer Link but i don't know to declare variable in json and how to fetch in PHP ? Thank you

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.