简体   繁体   中英

Rearrange Array Result of MySQLi Query

I have a MySQLi query that fetches data from my database in json format. Now I want to rearrange the result to form a new array using 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);

The result of this query is something like this:

[
  {
    "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"
  }
]

Now I want a result with something like this:

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

Can this be achieve in PHP? any help is appreciated.

You could store your data in separate arrays :

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

1.Since you didn't needed all data so do query like this:-

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

2.Change while loop code like below and you are done:-

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

So complete code need to be:-

$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);
<?php

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

 }
json_encode($user);
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM