使用php将数组添加到关联数组中

时间:2016-08-24 10:03:11

标签: php mysql arrays json

我有一个来自MySQL数据库记录的数组$项目:

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

我想用关键字"行"将它添加到关联数组$ result。

我试过这段代码

$ result [" rows"] = $ items;

但是print_r($ items);什么也没显示。

我最后想要的json是:

{
   "total":"105",
   "rows":[
      {
         "id":"3",
         "firstname":"fname1234BBBB",
         "lastname":"lname10....",
         "phone":"Lacock 4919999",
         "email":"name991@gmail.com"
      },

我做错了什么?感谢

1 个答案:

答案 0 :(得分: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;
        }