gpt4 book ai didi

php - 重新排列 MySQLi 查询的数组结果

转载 作者:太空宇宙 更新时间:2023-11-03 10:36:01 25 4
gpt4 key购买 nike

我有一个 MySQLi 查询,它以 json 格式从我的数据库中获取数据。现在我想使用 PHP 重新排列结果以形成一个新数组。

$conn = new mysqli("localhost", "root", "", "angular");

$out = array();

$sql = "SELECT * FROM members";
$query = $conn->query($sql);

while($row=$query->fetch_array()){
$out[] = $row;
}

echo json_encode($out);

这个查询的结果是这样的:

[
{
"0": "1",
"1": "Neovic",
"2": "Devierte",
"3": "Silay City",
"memid": "1",
"firstname": "Neovic",
"lastname": "Devierte",
"address": "Silay City"
},
{
"0": "2",
"1": "Julyn",
"2": "Divinagracia",
"3": "E.B. Magalona",
"memid": "2",
"firstname": "Julyn",
"lastname": "Divinagracia",
"address": "E.B. Magalona"
},
{
"0": "3",
"1": "Gemalyn",
"2": "Cepe",
"3": "Bohol",
"memid": "3",
"firstname": "Gemalyn",
"lastname": "Cepe",
"address": "Bohol"
},
{
"0": "4",
"1": "Tintin ",
"2": "Demapanag",
"3": "Talisy City",
"memid": "4",
"firstname": "Tintin ",
"lastname": "Demapanag",
"address": "Talisy City"
},
{
"0": "5",
"1": "Tintin ",
"2": "Devierte",
"3": "Silay City",
"memid": "5",
"firstname": "Tintin ",
"lastname": "Devierte",
"address": "Silay City"
}
]

现在我想要这样的结果:

[
firstname: {"Neovic", "Julyn", "Gemalyn", "Tintin", "Tintin"},
lastname: {"Devierte", "Divinagracia", "Cepe", "Demapanag", "Devierte"}
]

这可以用PHP实现吗?任何帮助表示赞赏。

最佳答案

您可以将数据存储在单独的数组中:

<?php
$firsts = [] ;
$lasts = [] ;
while ($row = $query->fetch_array()) {
$firsts[] = $row['firstname'] ;
$lasts[] = $row['lastname'] ;
}
$out = ['firstname' => $firsts, 'lastname' => $lasts] ;
?>

关于php - 重新排列 MySQLi 查询的数组结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48277361/

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