Reputation: 75
I have an array $items from records in a MySQL database:
$result = array();
$result["total"] = 105;
$sql = "SELECT id, firstname, lastname FROM users LIMIT 10, 20";
$result = $conn->query($sql);
$items = array();
while($row = mysqli_fetch_object($result)){
array_push($items, $row);
}
I want to add this to the associative array $result with the key "rows".
I have tried this code
$result["rows"] = $items;
but print_r($items); displays nothing.
The json that I want out at the end is:
{
"total":"105",
"rows":[
{
"id":"3",
"firstname":"fname1234BBBB",
"lastname":"lname10....",
"phone":"Lacock 4919999",
"email":"[email protected]"
},
What am I doing wrong ? Thanks
Upvotes: 0
Views: 103
Reputation: 2995
Try this code..
$resultArr = array();
$resultArr["total"] = 105;
$sql = "SELECT id, firstname, lastname FROM users LIMIT 10, 20";
$result = $conn->query($sql);
while($row = mysqli_fetch_object($result)){
$resultArr["rows"][] = $row;
}
echo json_encode($resultArr);
Upvotes: 0
Reputation: 1663
//First don't overwrite $result varaible.
$result_associative = array();
$result_associative["total"] = 105;
$sql = "SELECT id, firstname, lastname FROM users LIMIT 10, 20";
$result = $conn->query($sql);
$items = array();
while($row = mysqli_fetch_object($result)){
array_push($items, $row);
//push the item into array with associative key
$result_associative['rows'][] = $row;
}
Upvotes: 3