【问题标题】:Use foreach inside php array?在php数组中使用foreach?
【发布时间】:2021-01-24 00:49:24
【问题描述】:

有没有办法可以将此 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], "label" => date('H:i', $date[9])),
    array("y" => $last_ten_prices[8], "label" => date('H:i', $date[8])),
    array("y" => $last_ten_prices[7], "label" => date('H:i', $date[7])),
    array("y" => $last_ten_prices[6], "label" => date('H:i', $date[6])),
    array("y" => $last_ten_prices[5], "label" => date('H:i', $date[5])),
    array("y" => $last_ten_prices[4], "label" => date('H:i', $date[4])),
    array("y" => $last_ten_prices[3], "label" => date('H:i', $date[3])),
    array("y" => $last_ten_prices[2], "label" => date('H:i', $date[2])),
    array("y" => $last_ten_prices[1], "label" => date('H:i', $date[1])),
    array("y" => $last_ten_prices[0], "label" => date('H:i', $date[0])),
);

【问题讨论】:

    标签: php sql arrays foreach


    【解决方案1】:

    当然,像这样:

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

    如果您希望它以相反的顺序使用array_reverse($dataPoints),或更改查询中的顺序。

    【讨论】:

    • 谢谢劳伦斯·切罗内!
    • np,旁注:如果您不需要每一列,请不要使用`*`,您也可以使用SELECT SLI_price as y, DATE_FORMAT(SLI_date, '%H:%i') as label ...,然后可以取消foreach
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 2018-05-03
    • 2013-11-05
    • 2013-07-26
    • 1970-01-01
    • 2012-09-09
    • 1970-01-01
    相关资源
    最近更新 更多