MySQLi json_encode - 如何只获取字符串键而不是数字键?

时间:2014-03-06 05:48:18

标签: php json mysqli

使用json_encode只能获取带字符串的键而不是重复值而是使用数字键的条目?

这是SQL和PHP:

$stmt = $db->prepare("SELECT employee_profile.first_name,employee_profile.last_name, DATE(employee_timecard_entry.time_in_timestamp) AS date, employee_timecard_entry.hours_worked 
        FROM employee_timecard_entry, employee_profile WHERE time_in_timestamp BETWEEN ? AND ? AND employee_timecard_entry.employee_id = employee_profile.employee_id");
    $stmt->bind_param("ss", $left_side, $right_side);
    $stmt->execute(); 
    $result = $stmt->get_result();
    $data = array();

    while($row = mysqli_fetch_array($result))
       $data[] = $row;
    header('Content-type: application/json');
    echo json_encode($data);

输出样本:

[
    {
        "0": "Ashley",
        "1": "Boehme",
        "2": "2014-01-04",
        "3": "6.10",
        "first_name": "Ashley",
        "last_name": "Boehme",
        "date": "2014-01-04",
        "hours_worked": "6.10"
    },...

我更愿意只有最后4个条目而不是全部8个。我已经搜索过并找到了一种方法来使用PDO,但是我对这个项目太过分了,无法改变它。我也不想在客户端对它们进行排序,或者这是唯一的另一种方式吗?

1 个答案:

答案 0 :(得分:0)

您需要的是mysqli_fetch_assoc&不是mysqli_fetch_array

while($row = mysqli_fetch_assoc($result))