我正在尝试从mysql查询
创建多维数组查询:
$STH = $DBH->query( "SELECT value, o_ID, oName, date,
DATE_FORMAT(date, '%d %m %Y') as FDate,
DATE_FORMAT(tsTime, '%H:%i') as FTime
FROM test tst
LEFT JOIN object o
ON tst.o_ID =o.oID
WHERE DATE(date) = '$date'
ORDER BY FDate, FTime, oName ASC");
$STH->setFetchMode(PDO::FETCH_ASSOC);
循环:
$returnValue = array();
$data = array();
while ( $row = $STH->fetch() ) {
$returnValue[$row['oName']] =
array(
$data[] = array(
'time' => $row['FTime'], 'value' => $row['value']
)
);
}
输出:
{"objectA":[{"time":"23:55","value":"15"}],"objectB":[{"time":"23:55","value":"15.90"}],..}
如何将所有值都放在$ data数组中?
期望的输出:
{"objectA":[{"time":"01:00","value":"15"},{"time":"02:00","value":"11"},{"time":"03:00,"value":"16"}],"objectB":[{"time":""01:00","value":"12"},{"time":""02:00","value":"25"},{"time":""03:00","value":"5"}],..}
答案 0 :(得分:1)
试试这个:
while ( $row = $STH->fetch() ) {
$returnValue[] = array(
'time' => $row['FTime'], 'value' => $row['value']
);
}
答案 1 :(得分:1)
试一试:
$returnValue = array();
while ( $row = $STH->fetch() )
{
if (!$returnValue[$row['oName']])
{
$returnValue[$row['oName']] = array();
}
$returnValue[$row['oName']][]= array(
'time' => $row['FTime'], 'value' => $row['value']
);
}
那应该给你你想要的东西。
这里的区别在于,如果oName
- 键没有退出,我创建它,并为其分配一个新的空数组,然后我向该数组添加一个新的assiciative数组。
当行N的oName
已经有匹配的密钥时,我不打算重新分配该密钥,但我只是将一个额外的数组推送到该密钥。