简体   繁体   中英

MYSQL database to JSON format using PHP

I tried to convert get data from mysql in json format. For that I am using PHP.

My PHP code is

<?php 
define('_HOST_NAME', 'localhost');
define('_DATABASE_USER_NAME', 'root');
define('_DATABASE_PASSWORD', 'admin321');
define('_DATABASE_NAME', 'tree');

 $dbConnection = new mysqli(_HOST_NAME, 
     _DATABASE_USER_NAME, _DATABASE_PASSWORD, _DATABASE_NAME);

 if ($dbConnection->connect_error) {
      trigger_error('Connection 
      Failed: '  . $dbConnection->connect_error, E_USER_ERROR);
 }

 $_GLOBAL['dbConnection'] = $dbConnection;
    $categoryList = categoryParentChildTree(); 
    foreach($categoryList as $key => $value){
        echo $value['name'].'<br>';
 }

 function categoryParentChildTree($parent = 0, 
     $spacing = '', $category_tree_array = '') {
     global $dbConnection;
     $parent = $dbConnection->real_escape_string($parent);

 if (!is_array($category_tree_array))
    $category_tree_array = array();

 $sqlCategory = "SELECT id,name,parent FROM php WHERE parent = $parent ORDER BY id ASC";

 $resCategory=$dbConnection->query($sqlCategory);

 if ($resCategory->num_rows != null && $resCategory->num_rows>0) {

    while($rowCategories = $resCategory->fetch_assoc()) {
        $category_tree_array[] = array("id" => $rowCategories['id'],  "name" => $spacing . $rowCategories['name']);
        $category_tree_array = categoryParentChildTree(       
           $rowCategories['id'], 
           '&nbsp;'.$spacing . '-&nbsp;',  
           $category_tree_array
        );
    }
 }

 return  $category_tree_array;
}
?>

mysql table

      ID  PARENT  NAME
       1    0   category
       2    1   fruit
       3    2   apple
       4    2   orange
       5    1   animals
       6    5   tiger
       7    5   lion
       8    1   car

My output is:

  category 
       - fruit
         - - apple
         - - orange
       - animal
         - - tiger
         - - lion
       - cars

I want to get nested json output. Already asked here . No proper response.

I tried with json_encode, not getting nested json.

UPDATED PHP

   <?php
  $con=mysqli_connect("localhost","root","admin321","tree");       

     if (mysqli_connect_errno())                     //con error
       {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
      $r = mysqli_query($con,"SELECT * FROM php ");
    $data = array();
    while($row = mysqli_fetch_assoc($r)) {
     $data[] = $row;
     }  
     function buildtree($src_arr, $parent_id = 0, $tree = array())
 {
foreach($src_arr as $idx => $row)
{
    if($row['parent'] == $parent_id)
    {
        foreach($row as $k => $v)
            $tree[$row['id']][$k] = $v;
        unset($src_arr[$idx]);
        $tree[$row['id']]['children'] = buildtree($src_arr, $row['id']);
    }
}
ksort($tree);
return $tree;
}

     function insertIntoNestedArray(&$array, $searchItem){
// Insert root element
if($searchItem['parent'] == 0){
    array_push($array, $searchItem);
    return;
}
if(empty($array)){ return; }
  array_walk($array, function(&$item, $key, $searchItem){
if($item['id'] == $searchItem['parent']){
        array_push($item['children'], $searchItem);
        return;
    }
    insertIntoNestedArray($item['children'], $searchItem);
     }, $searchItem);
   }
     $nestedArray = array();
   foreach($data as $itemData){
// First: Mount the nested array item
$nestedArrayItem['id'] = $itemData['id'];
$nestedArrayItem['name'] = $itemData['name'];
$nestedArrayItem['parent'] = $itemData['parent'];
$nestedArrayItem['children'] = array();

// Second: insert the item into the nested array
insertIntoNestedArray($nestedArray, $nestedArrayItem);
      }
  $json = json_encode($nestedArray);
  echo $json;

  ?>

简单地说: json_encode($output , JSON_FORCE_OBJECT);

Your Nested Output is just an human-representation of the stored data you have in your database. Its a human thing. Machines can't understand that, that's why in mysql you need a column to tell the category parent.

So, your problem is that you're trying to convert to JSON your already manipulated data. You need to convert to JSON your raw data, and then manipulate it in the code that receives the JSON.

use json_encode to encode the raw data:

$raw_data = $resCategory->fetch_all();
return json_encode($raw_data);

Also, just a note: this $_GLOBAL variable you're using... you're not trying to refer to the internal php $GLOBALS superglobal, you are?


EDIT:

Ok, now that you explained that you need the nested json format, you will need to use some recursion to build an nested array of arrays and then use the json_encode on it.

First : Get the raw data:

$resCategory=$dbConnection->query($sqlCategory);
$raw_data = $resCategory->fetch_all();

Now, suppose this $raw_data variable returns an array like this:

array (
  0 => array (
    'ID' => 1,
    'PARENT' => 0,
    'NAME' => 'category',
  ),
  1 => array (
    'ID' => 2,
    'PARENT' => 1,
    'NAME' => 'fruit',
  ),
  2 => array (
    'ID' => 3,
    'PARENT' => 2,
    'NAME' => 'apple',
  ),
  3 => array (
    'ID' => 4,
    'PARENT' => 2,
    'NAME' => 'orange',
  ),
  4 => array (
    'ID' => 5,
    'PARENT' => 1,
    'NAME' => 'animals',
  ),
  5 => array (
    'ID' => 6,
    'PARENT' => 5,
    'NAME' => 'tiger',
  ),
  6 => array (
    'ID' => 7,
    'PARENT' => 5,
    'NAME' => 'lion',
  ),
  7 => array (
    'ID' => 8,
    'PARENT' => 1,
    'NAME' => 'car',
  )
)

Second : Build up an recursive function to insert items of this array into another array, the $nestedArray (that we will create in the third step).

function insertIntoNestedArray(&$array, $searchItem){
    // Insert root element
    if($searchItem['parent'] == 0){
        array_push($array, $searchItem);
        return;
    }

    // Stop the recursion when the array to check is empty
    if(empty($array)){ return; }

    // Walk the array searching for the parent of the search item
    array_walk($array, function(&$item, $key, $searchItem){
        // If the parent is found, then append the search item to it
        if($item['id'] == $searchItem['parent']){
            array_push($item['children'], $searchItem);
            return;
        }

        // If the parent wasn't found, walk thought the children of the array
        insertIntoNestedArray($item['children'], $searchItem);

    }, $searchItem);
}

Third : Create the $nestedArray and populate it by loop through the $raw_data array and calling the recursive function:

$nestedArray = array();
foreach($data as $itemData){
    // First: Mount the nested array item
    $nestedArrayItem['id'] = $itemData['ID'];
    $nestedArrayItem['name'] = $itemData['NAME'];
    $nestedArrayItem['parent'] = $itemData['PARENT'];
    $nestedArrayItem['children'] = array();

    // Second: insert the item into the nested array
    insertIntoNestedArray($nestedArray, $nestedArrayItem);
}

Fourth : Now its just to json_encode the $nestedArray :

$json = json_encode($nestedArray);

You can do an echo $json and the result will be:

[{"id":1,"name":"category","parent":0,"children":[{"id":2,"name":"fruit","parent":1,"children":[{"id":3,"name":"apple","parent":2,"children":[]},{"id":4,"name":"orange","parent":2,"children":[]}]},{"id":5,"name":"animals","parent":1,"children":[{"id":6,"name":"tiger","parent":5,"children":[]},{"id":7,"name":"lion","parent":5,"children":[]}]},{"id":8,"name":"car","parent":1,"children":[]}]}]

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