使用PHP

时间:2017-01-24 10:43:50

标签: php mysql json

我试图以json格式转换来自mysql的get数据。为此,我使用的是PHP。

我的PHP代码是

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

      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

我的输出是:

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

我想获得嵌套的json输出。已经问过here。没有适当的回应。

我试过json_encode,没有得到嵌套的json。

更新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;

  ?>

2 个答案:

答案 0 :(得分:0)

只需:json_encode($output , JSON_FORCE_OBJECT);

答案 1 :(得分:-1)

您的嵌套输出只是您在数据库中存储的数据的人类表示。这是一件人性化的事。机器无法理解,这就是为什么在mysql中你需要一个列来告诉父类别。

所以,您的问题是您尝试将已经处理过的数据转换为JSON。您需要将原始数据转换为JSON,然后在接收JSON的代码中对其进行操作。

使用json_encode对原始数据进行编码:

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

另外,只需注意:您正在使用的$_GLOBAL变量...您不是要尝试引用内部php $GLOBALS超全局,您是谁?

编辑:

好的,既然您已经解释过需要嵌套的json格式,那么您需要使用一些递归来构建嵌套的数组数组,然后在其上使用json_encode

首先:获取原始数据:

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

现在,假设此$raw_data变量返回如下数组:

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',
  )
)

第二:构建一个递归函数,将此数组的项插入另一个数组$nestedArray(我们将在第三步中创建)。

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);
}

第三次:创建$nestedArray并通过$raw_data数组循环填充并调用递归函数:

$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_encode $nestedArray

$json = json_encode($nestedArray);

你可以做一个echo $json,结果将是:

[{"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":[]}]}]