我有一个包含两列数据和几行的mysqli结果集。我想将结果集的每一行存储为结果数组中的索引子数组(特别是在$rows['data']
中)。
这是我目前的代码:
$query = mysqli_query($con,"SELECT Energy_UTC,Total_watts FROM combined_readings");
$rows = array();
$rows['name'] = 'Total_watts';
while ($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = $tmp['Energy_UTC'];
$rows['data'][] = $tmp['Total_watts'];
}
这会产生一个如下所示的数组:
{"name":"Total_watts","data":[1519334969,259,1519335149,246,1519335329,589,1519335509,589,1519335689,341,1519335869,341,1519336050,523,1519336230,662,1519336410,662,1519336590,469]}
但我需要结果是一个如下所示的数组:
{"name":"Total_watts","data":[1519334969,259],[1519335149,246],[1519335329,589],[1519335509,589],[1519335689,341],[1519335869,341],[1519336050,523],[1519336230,662],[1519336410,662],[1519336590,469]}
有人建议改变PHP while循环以产生此输出吗?
答案 0 :(得分:1)
您只需调整语法以将元素放在同一个子数组中。
while($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = [$tmp['Energy_UTC'],$tmp['Total_watts']];
}
P.S。此外,您可以使用mysqli_fetch_assoc()
,因为您只访问关联键。或者甚至更好,使用mysqli_fetch_row()
并将行分配给结果数组。
全部烘焙,它可能看起来像这样:
if(!$result=mysqli_query($con,"SELECT Energy_UTC,Total_watts FROM combined_readings")){
// handle the query error
}else{
$rows=['name'=>'Total_watts'];
while($row=mysqli_fetch_row($result)){
$rows['data'][]=$row; // this will store subarrays like: [1519334969,259]
}
}