0

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

2
  • What does print_r($result) display ? Commented Aug 24, 2016 at 10:08
  • use $result["rows"][] = $row; inside the loop Commented Aug 24, 2016 at 10:08

2 Answers 2

3
    //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;
        }
Sign up to request clarification or add additional context in comments.

3 Comments

remove this line inside the loop array_push($items, $row);
@devpro, he might use this variable for something else.
Thanks Kristiyan - works as I wanted. Thanks for the comment lines.
0

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

1 Comment

@peter300 welcome dear glad to help you please up vote and accept the helpful answer so that is makes easy for future users to choose the best answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.