【问题标题】:MySQLi json_encode - how to get only string key not the numeric key?MySQLi json_encode - 如何只获取字符串键而不是数字键?
【发布时间】:2014-03-06 05:48:18
【问题描述】:

当使用 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 执行此操作的方法,但我对这个项目的了解太远了,无法更改。我也不想在客户端对它们进行排序,或者这是唯一的其他方式?

【问题讨论】:

    标签: php json mysqli


    【解决方案1】:

    你需要的是mysqli_fetch_assoc 而不是mysqli_fetch_array

    while($row = mysqli_fetch_assoc($result))
    

    【讨论】:

    • 哇...好简单啊。谢谢
    猜你喜欢
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 2017-11-23
    • 2019-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多