如何将值插入多维数组中,然后显示它们


How do I insert values into an multidimensional-array, then show them?

我对php还很陌生,不知道如何很好地处理数组。这是一个交易,我想在一个多维数组中添加三个或更多从数据库中获得的值,然后我想根据时间戳(其中一个值)对它们进行排序。之后,我想显示所有排序后的值。我似乎做不到,这是代码

    $queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, Order, Classification FROM exams WHERE (CurrentState = "Pending")';
    $results = mysql_query($queryWaitingPatients) or die(mysql_error());
    if (mysql_num_rows($results) == 0) {
        echo '<p>There''s currently no patient on the waiting list.</p>';
        return;
    }
    while ($rows = mysql_fetch_array($results)) {
        extract($rows);
    //now is the part that I don't know, putting the values into an array
    }
    // I'm also not sure how to sort this according to my $TargetTime
    asort($sortedTimes);
     //the other part I don't know, showing the values, 

谢谢你的帮助!

好吧,让我们看看您的代码。首先,您有一个返回结果集的查询。我不建议使用mysql_fetch_array,因为它不仅不推荐使用(而是使用mysqli函数),而且它往往会导致糟糕的代码。当你所有的钥匙都是数字时,很难弄清楚你指的是什么。因此,我推荐mysqli_fetch_assoc(确保首先完全切换到mysqli函数,如mysql_connectmysqli_query

其次,我真的不喜欢使用提取物。我们需要直接使用数组。以下是我们如何进行

$myarray = array();
while ($rows = mysqlI_fetch_assoc($results)) {
    $myarray[] = $rows;
}
echo $myarray[0]['ArrivalTime'];

让我们来复习一下。首先,我们正在构建一个数组。因此,我们初始化我们的整体array。然后我们想把行推到这个数组上。$myarray[]就是这么做的。最后,我们推送的数组是关联的,这意味着行的所有键都与查询的字段名匹配。

现在,排序确实需要在查询中完成。因此,让我们调整您的查询

$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, `Order`, Classification 
    FROM exams 
    WHERE CurrentState = "Pending"
    ORDER BY TargetTime';

这样,当您的PHP运行时,您的数据库现在会按照数组的正确顺序来生成它们。不需要排序代码。

$arr = array(); 
while ($rows = mysql_fetch_array($results)) {
     array_push ($arr, $row);
}
print_r($arr);
<?php
$queryWaitingPatients = ' SELECT ArrivalTime, TargetTime, Order, Classification, CurrentState 
                          FROM exams 
                          WHERE CurrentState = "Pending"
                          ORDER BY TargetTime ';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
    if ($results -> num_rows < 1)
    {
        echo '<p>There''s currently no patient on the waiting list.</p>';
     }
     else
    {
     while ($rows = mysqli_fetch_array($results))
       {
         $arrivaltime = $row['ArrivalTime'];
         $targettime = $row['targettime'];
         $order = $row['Order'];
         $classification = $row['Classification'];
         echo   "Arrival: ".$arrivaltime."--Target time: ".$targettime."--Order: ".$order."--Classification: ".$classification;
        }
     }
echo "Done!";
//or you could put it in a json array and pass it to client side.
?>