从选择查询中创建键值对

时间:2014-01-15 17:18:05

标签: php

我收到了这个回复

{"id":"40","roomno":"118"}{"id":"41","roomno":"119"}

来自我的php函数

/** 
 * Binding rooms to dropdown
 */
if(isset($_GET['beds']) && isset($_GET['type'])){
    $room_type = $_GET['type'];
    $number_of_beds = $_GET['beds'];
    $bind_rooms = new Rooms;
    $results = $bind_rooms->Bind_Rooms($room_type, $number_of_beds);
    while ($row = $results->fetch_assoc()){
        echo json_encode($row);
    }


}

我怎么试图实现

 {"40":"118"}{"41":"119"}

无论如何我们可以从数据库中获取记录作为键值对而不是列名作为键吗?我从早上起就一直在尝试这样做:S

1 个答案:

答案 0 :(得分:4)

echo json_encode(
    array_combine(
        array($row['id']), 
        array($row['roomno'])
    )
);

甚至只是

echo json_encode(
    array(
        $row['id'] => $row['roomno']
    )
);