0

从涉及多个 JOINS 的 MySQL 查询中创建表示表的 JSON 树的最干净和最有效的方法是什么?

在此处输入图像描述

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

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

然后我可以做 echo $arr[2]["sold"] 并得到“2 sodas”

4

1 回答 1

0

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

    $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);
于 2013-08-12T04:44:08.903 回答