在PHP数组中使用foreach吗?

问题描述

有没有办法将这个foreach放在数组中? 现在,我有这个丑陋的解决方案。

$date = [];
$query = $pdo -> prepare('SELECT * FROM stock_list WHERE SLI_type = :type ORDER BY SLI_date DESC LIMIT 11');
$query -> execute(array(':type' => $_GET['aksjegraf']));
foreach ($query as $row) {
    array_push($last_ten_prices,$row['SLI_price']);
    array_push($date,$row['SLI_date']);
}

$dataPoints = array(
    array("y" => $last_ten_prices[10],"label" => date('H:i',$date[10])),array("y" => $last_ten_prices[9],$date[9])),array("y" => $last_ten_prices[8],$date[8])),array("y" => $last_ten_prices[7],$date[7])),array("y" => $last_ten_prices[6],$date[6])),array("y" => $last_ten_prices[5],$date[5])),array("y" => $last_ten_prices[4],$date[4])),array("y" => $last_ten_prices[3],$date[3])),array("y" => $last_ten_prices[2],$date[2])),array("y" => $last_ten_prices[1],$date[1])),array("y" => $last_ten_prices[0],$date[0])),);

解决方法

当然可以,

foreach ($query as $row)
  $dataPoints[] = ["y" => $row['SLI_price'],"label" => date('H:i',$row['SLI_date'])];

如果您想要相反的顺序,请使用array_reverse($dataPoints),或在查询中更改顺序。