[英]populate multidimensional array from MySQL query
I am trying to create multidimensional array from MySQL query 我试图从MySQL查询创建多维数组
Query: 查询:
$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);
Loop: 环:
$returnValue = array();
$data = array();
while ( $row = $STH->fetch() ) {
$returnValue[$row['oName']] =
array(
$data[] = array(
'time' => $row['FTime'], 'value' => $row['value']
)
);
}
Output: 输出:
{"objectA":[{"time":"23:55","value":"15"}],"objectB":[{"time":"23:55","value":"15.90"}],..}
how can I put all values in $data array? 如何将所有值放在$ data数组中?
Desired output: 期望的输出:
{"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"}],..}
Try this: 尝试这个:
while ( $row = $STH->fetch() ) {
$returnValue[] = array(
'time' => $row['FTime'], 'value' => $row['value']
);
}
Give this a shot: 试一试:
$returnValue = array();
while ( $row = $STH->fetch() )
{
if (!$returnValue[$row['oName']])
{
$returnValue[$row['oName']] = array();
}
$returnValue[$row['oName']][]= array(
'time' => $row['FTime'], 'value' => $row['value']
);
}
That should give you what you want. 这应该给你你想要的。
The difference here is that, if the oName
-key doesn't exits, I create it, and assign it a new, empty array, then I add a new assiciative array to that array. 这里的区别在于,如果oName
没有退出,我创建它,并为它分配一个新的空数组,然后我向该数组添加一个新的assiciative数组。
When the oName
of row N already has a matching key, I'm not going to reassign that key, but I'm just going to push an extra array to that key. 当行N的oName
已经有匹配的键时,我不打算重新分配该键,但我只是将一个额外的数组推送到该键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.