在PHP中循环并存储关联数组中的键值



我正试图从SQL查询创建的PHP关联数组中提取值

SELECT WEEKDAY(Date) AS weekday, 100 * SUM(Att_Type) / COUNT(Att_Type) AS percentage 
FROM Attendance 
WHERE ID=$ID AND WEEK(Date) = WEEK(NOW()) 
GROUP BY WEEKDAY(Date)

它与我使用CCD_ 2命令找到的内容一起存储在变量CCD_

Array ( [weekday] => 2 [percentage] => 100.0000 ) 
Array ( [weekday] => 1 [percentage] => 100.0000 ) 
Array ( [weekday] => 0 [percentage] => 66.6667 ) 
Array ( [weekday] => 3 [percentage] => 100.0000 )

我是PHP关联数组的新手,我想知道如何创建一个函数,它将接受工作日键的值,如果它是0(星期一(,则将百分比键的值存储在星期一变量中,依此类推,直到4(星期五(为止的其余工作日值都可用。

编辑:

我正在寻找的输出是将值保存为自变量的地方,因此当调用时,它们会清楚地显示值,例如:

$monday = 66.6667
$tuesday = 100.0000
$wednesday = 100.0000
$thursday = 100.0000
$friday = 0 //when there is no value corresponding to that weekday in the array then it will be 0

因此它们可以在稍后的代码中得到响应。

$data = [['weekday' => 2, 'percentage' => 100.0000,], ['weekday' => 1, 'percentage' => 100.0000,], ['weekday' => 0, 'percentage' => 66.6667,], ['weekday' => 3, 'percentage' => 100.0000,]];    
$days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
foreach ($days as $day) {
${$day} = 0;
}

如果您使用$results = mysqli_fetch_all($result, MYSQLI_ASSOC)来获得结果的数组,请使用此;

$results = mysqli_fetch_all($result, MYSQLI_ASSOC);
foreach($results as $arr) {
${$days[$arr['weekday']]} = $arr['percentage'];
// $arr['weekday'] gets the weekday of the array;
// $days[$arr['weekday']] gets the day index from the days array
// ${$days[$arr['weekday']]} then creates a variable with the particular weekday as the variable name
}

或者如果您使用的是while ($arr = mysqli_fetch_assoc($result))

while ($arr = mysqli_fetch_assoc($result)) {
${$days[$arr['weekday']]} = $arr['percentage'];
}

最新更新