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

时间:2018-01-16 08:56:48

标签: php mysql json mysqli

我有一个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实现吗?任何帮助表示赞赏。

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

1.由于您不需要所有数据,所以请像这样查询: -

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

2.改变循环代码,如下所示: -

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);

答案 2 :(得分:1)

<?php

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

 }
json_encode($user);
?>