Json仅响应值,但需要键+值

时间:2014-10-09 01:02:07

标签: php mysql arrays json

以下PHP代码仅转换值,但我还需要每个值的键:

应该如何(期望的输出):

[{"ID":"1","styleNo":"1","styleName":"Casual","placeholder":"Left Initial","type":"text","maxlength":"1","size":"small","position":"1"},{"ID":"2","styleNo":"1","styleName":"Casual","placeholder":"Right Initial","type":"text","maxlength":"1","size":"small","position":"2"},{"ID":"3","styleNo":"1","styleName":"Casual","placeholder":"Center Initial","type":"text","maxlength":"1","size":"small","position":"3"}]

实际情况如何(我不知道不同的括号是否重要?):

[["1","1","Casual","Left Initial","text","1","small","1"],["2","1","Casual","Right Initial","text","1","small","2"],["3","1","Casual","Center Initial","text","1","small","3"]]

<?php
$style = $_GET['style'];
define('HOST', 'localhost');
define('USER', 'root');
define('PASS', '');
define('DBNAME', 'inscribe');

$db = new mysqli(HOST, USER, PASS, DBNAME);

if (mysqli_connect_errno()) {
    printf("Connect failed: %s<br/>", mysqli_connect_error());
}

$sql = "SELECT * FROM inputs WHERE styleNo = '".$style."'";
$result_db = $db->query($sql);
$all_result = $result_db->fetch_all();
echo json_encode($all_result);
$db->close();
?>

2 个答案:

答案 0 :(得分:3)

尝试在MYSQLI_ASSOC中将mysql fetch标志显式设置为fetch_all(),因为它的默认值为MYSQLI_NUM,它返回数字索引而不是关联。

示例:

$all_result = $result_db->fetch_all(MYSQLI_ASSOC);
echo json_encode($all_result);

旁注:转义输入或使用预准备语句:

$style = $db->real_escape_string($_GET['style']);
$sql = "SELECT * FROM inputs WHERE styleNo = '$style' ";
$result_db = $db->query($sql);
$all_result = $result_db->fetch_all(MYSQL_ASSOC);
echo json_encode($all_result);

或者

$sql = "SELECT * FROM inputs WHERE styleNo = ?";
$select = $db->prepare($sql);
$select->bind_param('s', $_GET['input']);
$select->execute();
$result = $select->get_result();
$all_result = $result->fetch_all(MYSQL_ASSOC);
echo json_encode($all_result);

答案 1 :(得分:-1)

它正在做它应该做的事情。 sql查询返回结果行,以便它提供给你的东西。快速解决方案

$tmp = array();
$keys = array("ID", "styleNo", "placeholder", "type", "maxlength", "size", "position");
foreach($all_result as $row){
     $tmp[] = array_combine($keys, $row);
}

echo json_encode($tmp);

如果您的选择更改可能会中断。