重新排列mysqli查询的数组结果

fcy6dtqo  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(310)

我有一个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实现吗?感谢您的帮助。

dwbf0jvd

dwbf0jvd1#

<?php

$i=0;
while ($row = $query->fetch_array())
{
    $user[$i]['first_name'] = $row['firstname'] ;
    $user[$i]['last_name'] = $row['lastname'] ;
   $i++;

 }
json_encode($user);
?>
o2gm4chl

o2gm4chl2#

您可以将数据存储在不同的数组中:

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

lc8prwob3#

1.由于您不需要所有数据,所以请执行如下查询this:-

$sql = "SELECT firstname,lastname FROM members";

2.像下面这样改变循环代码done:-

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

所以完整的代码必须是:-

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

$out = array();

$sql = "SELECT firstname,lastname FROM members";
$query = $conn->query($sql);

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

echo json_encode($out);

相关问题