问题 我通过选择每个数据集并逐行输出来输出一组数据。
问题 是否有一种获取此数据并将其存储为数组的方法,然后我可以将其转换为字符串值集合?
$sql = "SELECT * FROM respondent_data WHERE respondent_firstname = 'John'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$categoriesTest[] = $row["respondent_sdo"];
$row["respondent_dcto"];
$row["respondent_ed"];
$row["respondent_ca"];
$row["respondent_dhpt"];
$row["respondent_irt"];
$row["respondent_gl"];
$row["respondent_il"];
// Turn my output into an array ready to be used for the JSON string
}
}
示例
所以这些值中的每一个都从我需要它们的列行输出一个整数,以便变成一个数组,如:2,4,3,5 ....
答案 0 :(得分:0)
这应该可以解决问题。
$sql = "SELECT * FROM respondent_data WHERE respondent_firstname = 'John'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$i=0;
while($row = mysqli_fetch_assoc($result)) {
$categoriesTest[$i]["respondent_sdo"] = $row["respondent_sdo"];
$categoriesTest[$i]["respondent_dcto"] = $row["respondent_dcto"];
$categoriesTest[$i]["respondent_ed"] = $row["respondent_ed"];
$categoriesTest[$i]["respondent_ca"] = $row["respondent_ca"];
$categoriesTest[$i]["respondent_dhpt"] = $row["respondent_dhpt"];
$categoriesTest[$i]["respondent_irt"] = $row["respondent_irt"];
$categoriesTest[$i]["respondent_gl"] = $row["respondent_gl"];
$categoriesTest[$i]["respondent_il"] = $row["respondent_il"];
$i++;
}
var_dump($categoriesTest);
}
答案 1 :(得分:0)
如果您只想要从MySQL调用中查询的所有列中的特定关联属性,只需将它们设置在具有各自属性的数组中:
$categoriesTest = array();
$sql = "SELECT * FROM `respondent_data` WHERE `respondent_firstname` = 'John'";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
$categoriesTest[] = array(
'respondent_sdo' => $row['respondent_sdo'],
'respondent_dcto' => $row['respondent_dcto'],
'respondent_ed' => $row['respondent_ed'],
'respondent_ca' => $row['respondent_ca'],
'respondent_dhpt' => $row['respondent_dhpt'],
'respondent_irt' => $row['respondent_irt'],
'respondent_gl' => $row['respondent_gl'],
'respondent_il' => $row['respondent_il']
);
}
$categoriesTest = json_encode($categoriesTest); // get JSON
但是,如果您想要查询所有列,但要创建自定义元素,则您需要使用array_merge:
$categoriesTest = array();
$sql = "SELECT * FROM `respondent_data` WHERE `respondent_firstname` = 'John'";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
$categoriesTest[] = array_merge($row, array(
'custom_value_1' => 'test',
'custom_value_2' => 'test2'
));
}
$categoriesTest = json_encode($categoriesTest); // get JSON