gpt4 book ai didi

php - 从 Mysql 创建嵌套数组

转载 作者:行者123 更新时间:2023-11-29 02:21:38 25 4
gpt4 key购买 nike

我正在尝试从 mysql 获取正确的 Json 数据。我取得了很大进步。看一看;

我有如下表格:

name             folder    path
RayMala 787 01.jpg,02.jpg,03.jpg,04.jpg,05.jpg...
RayMala 788 01.jpg,02.jpg,03.jpg,04.jpg,05.jpg,06.jpg...
Falitiko 332 01.jpg...
Falitiko 333 01.jpg,02.jpg...

我当前的代码:从单个表格单元格创建数组。

$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}

$nArray = array();
foreach($rows as $value){
$nArray[] = array('name' => $value['name'], 'folder' => $value['folder'], 'path' => explode(",", $value['path']));
}

print json_encode($nArray);

当前 JSON 输出:查看名称值重复。

[
{
"name": "RayMala",
"folder": "787",
"Paths": ["1.jpg", "2.jpg", "3.jpg"]
},
{
"name": "RayMala",
"folder": "788",
"Paths": ["1.jpg", "2.jpg", "3.jpg"]
},
{
"name": "Falitiko",
"folder": "333",
"Paths": ["1.jpg", "2.jpg", "3.jpg"]
}
]

需要的 JSON 输出:

[
{
"name":"RayMala",
"random": [
{
"folder": "787",
"Paths": ["1.jpg", "2.jpg", "3.jpg"]
},
{
"folder": "788",
"Paths": ["1.jpg", "2.jpg", "3.jpg"]
}
]
},
{
"name":"Falitiko",
"random": [
{
"folder": "332",
"Paths": ["1.jpg", "2.jpg", "3.jpg"]
},
{
"folder": "333",
"Paths": ["1.jpg", "2.jpg", "3.jpg"]
}
]
}
]

最佳答案

$nArray = array();
while($r = mysqli_fetch_assoc($result)) {
$nArray[$r["name"]][] = array('folder' => $r['folder'], 'path' => explode(",", $r['path']));
}
$output_arr = array();
foreach($nArray as $key=>$value){
$output_arr[]=array("name"=>$key,"random"=>$value);
}
echo json_encode($output_arr);

关于php - 从 Mysql 创建嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30817695/

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