0

我正在尝试从 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"}],..}
4

2 回答 2

1

试试这个:

while ( $row = $STH->fetch() ) {
    $returnValue[] = array(
       'time' => $row['FTime'], 'value' => $row['value']
      );
    }  
于 2013-06-28T08:51:02.980 回答
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-key 不存在,我创建它,并为其分配一个新的空数组,然后我向该数组添加一个新的关联数组。
oName第 N 行已经有一个匹配的键时,我不会重新分配该键,但我只是要将一个额外的数组推送到该键。

于 2013-06-28T09:04:42.580 回答