gpt4 book ai didi

php - 从 MySQL 查询构建数组以格式化 json

转载 作者:行者123 更新时间:2023-11-30 22:54:19 25 4
gpt4 key购买 nike

我在根据预期的 json 格式从 mysql 结果构建正确的数组时遇到了问题:

表格:

    CREATE TABLE `Config_Category` (    `id` INT(11) NOT NULL AUTO_INCREMENT,    `name` VARCHAR(50) NOT NULL DEFAULT '0',    `topid` INT(8) NOT NULL DEFAULT '0',    PRIMARY KEY (`id`)    )    ;

filled table:

id  name        topid2   DVD         13   Matrix      24   CD          15   Deep Purple 46   Pink Floyd  47   Batman      2
MyClass
{
public function getMenu($topid)
{

$stmt = $this->pdoDash->query("SELECT id,name
FROM Config_Category WHERE topid='$topid'");

$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($results as $row)
{
if ($this->hasChildKats($row['id']))
{
$path[] = array("group" => $row['name']);
$path[] = array_merge($this->getMenu($row['id'], $path));

} else
{
$path["item"][] = array("name" => $row['name']);

}
}
return $path;
}

private function hasChildKats($katID)
{
$stmt = $this->pdoDash->query("SELECT count(*)
FROM Config_Category WHERE topid='$katID'");

return $stmt->fetchColumn();
}
}

$this->test = new MyClass;
echo json_encode($this->test->getMenu());

我的结果:

[
{
"group": "DVD"
},
{
"item": [
{
"name": "Matrix"
},
{
"name": "Batman"
}
]
},
{
"group": "CD"
},
{
"item": [
{
"name": "Pink Floyd"
},
{
"name": "Deep Purple"
}
]
}
]

预期结果:

[
{
"group": "DVD",
"item": [
{
"name": "Matrix"
},
{
"name": "Batman"
}
]
},
{
"group": "CD",
"item": [
{
"name": "Pink Floyd"
},
{
"name": "Deep Purple"
}
]
}
]

最佳答案

在我看来,使用空括号 [] 是导致此行为的原因。您应该尝试使用变量作为计数器:

var $counter = 0;

foreach ($results as $row)
{
if ($this->hasChildKats($row['id']))
{
$path[$counter] = array("group" => $row['name']);
$path[$counter] = array_merge($this->getMenu($row['id'], $path));

} else
{
$path["item"][$counter] = array("name" => $row['name']);
}
$counter++;
}

关于php - 从 MySQL 查询构建数组以格式化 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27051869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com