【问题标题】:MYSQL database to JSON format using PHPMYSQL数据库使用PHP转JSON格式
【发布时间】:2017-01-25 15:24:53
【问题描述】:

我尝试将 mysql 中的获取数据转换为 json 格式。为此,我正在使用 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;

  ?>

【问题讨论】:

  • @YIVI 我在问题中提到过..请去看看..
  • 同一个问题问两次不好,只会增加噪音。如果您没有收到回复,请处理您的问题。
  • 上一个问题已更新

标签: php mysql json


【解决方案1】:

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

【讨论】:

  • 感谢您的回复先生..但输出是致命错误:未捕获的错误:C:\Apache24\htdocs\index.php:32 中的字符串不支持 [] 运算符堆栈跟踪:#0 C :\Apache24\htdocs\index.php(33): categoryParentChildTree('2', '  -&n...', '{"0":{"id":"1",...' ) #1 C:\Apache24\htdocs\index.php(33): categoryParentChildTree('1', ' - ', Array) #2 C:\Apache24\htdocs\index.php(17): categoryParentChildTree () #3 {main} 在 C:\Apache24\htdocs\index.php 第 32 行抛出
  • @programmer 看起来那是另一个错误。你能告诉我第 32 行的内容吗?
  • 非常抱歉先生,现在我手头没有密码……明天我到办公室时会立即显示该行
  • 这里是 $category_tree_array[] = array("id" => $rowCategories['id'], "name" => $spacing . $rowCategories['name']); //第 32 行
  • 您是否尝试过打印 $rowCategories 变量?
【解决方案2】:

您的嵌套输出只是您在数据库中存储的数据的人工表示。它是人类的东西。机器无法理解,这就是为什么在 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);

你可以回显$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":[]}]}]

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-21
  • 1970-01-01
  • 2017-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多