正确的多维数组格式以获取输出(如果存在)


Correct Multidimensional array format to get output if exists

好吧,我可能以错误的方式处理这个问题,所以在我进一步讨论之前,我想我会咨询一些专家。

以前,在搜索数据库后,我会创建一个带有日期数组名称的数组,每个日期只有 1 个数组。 然后可以调用它并将其显示在日历的相应部分。但是现在每个日期可能有多个条目,我正在尝试更改为多维数组。

$stmt = $dbc->prepare("SELECT stoname, date, hours1, hours2 FROM table WHERE MONTH(date)=? AND YEAR(date)=?");
$stmt->bind_param("ss", $month, $year);
$stmt->execute();
$stmt->bind_result($sto_name, $DB_date, $hours1, $hours2);
while ($stmt->fetch())
{
//Loop through to make new array corresponding to date in database
$foo="_".str_replace("-","",$DB_date);      //take the "-" outta the date
${$foo}[$sto_name]=array(
                    'sto_name'=>$sto_name,
                    'hours1'=>$hours1,
                    'hours2'=>$hours2);
}
$stmt->close();

我不确定这是否是最好的方法,尽管它似乎确实工作正常。 但是,由于[$sto_name]未知,因此很难访问数组,并且似乎我无法使用数字位来调用关联数组,例如 $20160316[0] . 在输出中,我需要检查该日期是否存在数组,而不考虑 [$sto_name],然后可以打印数组。

我想过这样的事情:

${$foo}=array(
                    array(
                    'sto_name'=>$sto_name,
                    'hours1'=>$hours1,
                    'hours2'=>$hours2),
                    );

但是在 mysqli while 循环上,如果有第二个具有相同日期/$foo的数组,它可能会覆盖第一个数组。

正如你所说:-"但是在mysqli while循环中,如果有第二个数组具有相同的date/$foo,它可能会覆盖第一个数组"

所以你需要把${$foo}[$sto_name]改成${$foo}[$sto_name][].

最好是使用${$foo}[]而不是${$foo}[$sto_name]

注意:- 它在两种情况下都可以正常工作:- 您获得单个数据或多个数据。