【问题标题】:Loop and store key value from associative array in PHP [closed]在 PHP 中循环并存储关联数组中的键值 [关闭]
【发布时间】:2021-06-09 20:37:06
【问题描述】:

我正在尝试从我通过 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)

它被存储在变量$arr 中,其中包含我使用print_r 命令找到的内容:

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

因此它们可以在稍后的代码中回显。

【问题讨论】:

  • this 之类的东西可能会有所帮助。使用数组将“索引”映射到天数。
  • 您能否编辑您的问题以包含您正在寻找的输出类型的明确示例?要么显示一个代码示例,说明你想在最后定义哪些变量,或者你想输出什么文本。
  • @jibsteroos 我真的很喜欢这个例子,但我一直收到错误“警告:foreach() 参数必须是数组|对象类型,给定字符串”

标签: php sql arrays associative-array


【解决方案1】:
$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'];
}

【讨论】:

  • foreach 循环中的错误行吗? @McKenzieJo
  • 干杯伙伴 :) @WOUNDEDStevenJones
  • 首先在 $days 上执行一次 foreach(或 array_map)以将所有“day”变量初始化为 0 会有所帮助。
  • @a.mola 哇!!好的,我让它在一个单独的文件中工作,它是完美的!我发现了为什么会出现这些错误;我试图在一段时间内使用此语句($arr = mysqli_fetch_assoc($result)) 从数据库中获取数据,而 $arr 与您的代码不匹配。我需要弄清楚为什么它的行为方式不同:/有什么想法吗?
  • 您可以致电$array = (mysqli_fetch_all($result), MYSQLI_ASSOC) 一次获取所有记录行,或者查看我编辑的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-24
  • 2014-01-11
  • 2019-07-01
  • 2013-07-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多