从平面 PHP SQL 表制作 JSON 树 [英] Making a JSON tree from a flat PHP SQL table

查看:47
本文介绍了从平面 PHP SQL 表制作 JSON 树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从涉及多个 JOINS 的 MySQL 查询创建表示表的 JSON 树的最简洁、最有效的方法是什么?

What would be the cleanest and most efficient way to create a JSON tree representing a table from a MySQL query involving multiple JOINS ?

到目前为止,php数组是由这个循环创建的:

So far, the php array is created by this loop:

$rs = mysqli_query($connect, $query);
$arr = array();
while ($row = mysqli_fetch_array($rs, MYSQL_ASSOC)) {
    $arr[] = $row;
}

然后我可以执行 echo $arr[2]["sold"] 并获得2 sodas"

I could then do echo $arr[2]["sold"] and get "2 sodas"

推荐答案

好吧,这是我自己的问题的解决方案!...为了所有人的利益!!!它正在工作,但有人可以提出更好更快的方法吗?

Well here is my own solution to my own question !... For the benefits of ALL !!! It is working but can anyone suggest a better faster approach ?

    $rs = mysqli_query($connect, $query);
$arr = array();
while ($row = mysqli_fetch_array($rs, MYSQL_ASSOC)) {

    $arr[] = $row;
}
$dateLevel = 0;
$employeeLevel = 0;
$soldLevel = 0;
$tree = array();
$count = count ($arr);
for ($i = 0; $i < $count; $i++){

    $A = $tree[$dateLevel-1];
    if ($A["text"] != $arr[$i]["date"]){
        $tree[$dateLevel]= array("text" => $arr[$i]["date"],  "expanded" => true, items => array());
        $dateLevel++;
        $employeeLevel = 0;
        $soldLevel = 0;
    }

    $A = $tree[$dateLevel-1];
    $B = $A["items"];
    $C = $B[$employeeLevel-1];
    if ($C["text"]  != $arr[$i]["employee"]){
        $tree[$dateLevel-1]["items"][$employeeLevel] = array ("text" => $arr[$i]["employee"],  "expanded" => true, items => array());
        $employeeLevel++;
        $soldLevel = 0;
    }

    $A = $tree[$dateLevel-1];
    $B = $A["items"];
    $C = $B[$employeeLevel-1];
    $D = $A["items"];
    if ($D["text"]  != $arr[$i]["sold"]){
        $tree[$dateLevel-1]["items"][$employeeLevel-1]["items"][$soldLevel] = array ("text" => $arr[$i]["sold"],  "expanded" => true, items => array());
        $soldLevel++;
    }
}

echo json_encode($tree);

这篇关于从平面 PHP SQL 表制作 JSON 树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆