【问题标题】:How can I assign a number to access assigned array value?如何分配一个数字来访问分配的数组值?
【发布时间】:2017-06-19 13:14:36
【问题描述】:

我将结果存储在一个多维数组中,一些值由具有数值 ex 的变量标识。 $end1 = "2017-01-08";每个日期下都有大约 10 个类别,用于存储一个数值。 我需要遍历 $end1 下的所有值才能得到总数。

这行得通:

foreach($results[$key][$end1] as $type => $amount) {
    $total1 += $amount[$value];
}

但现在我有一堆这样的 foreach 语句 - 我需要的每个总数都有一个 - 我想将它们合并到一个块中,但我无法正确获取变量名。

这不起作用:

    for($i = 1; $i <= 4; $i++){
        $target = "\$end$i";
        $targettotal = "\$total$i";
        foreach($results[$key][$target] as $type => $amount) {
            $targettotal += $amount[$value];
        }            
    }

如何修复/定义 $target 和 $targettotal 以便可以访问数组值?

【问题讨论】:

  • 这是一个选项:$target .= "\$end$i"; $targettotal .= "\$total$i";你为什么要转义美元符号 \$ ?
  • 不完全确定您的意思,但您想打印输出还是将 $total 和 $targettotal 的输出保存在一个数组中?并且确实想访问它,例如$total[$i] = '输出';

标签: php arrays variables


【解决方案1】:

看看下面的演示,注意下一行中对 $targetVarName 的评估,在它前面加上另一个美元符号。

<?php

$item1 = 'aaa';
$item2 = 'bbb';
$item3 = 'ccc';
$item4 = 'ddd';
$item5 = '333';

for ($i = 1; $i < 6; $i++) {

    $targetVarName = 'item' . $i;

    echo $targetVarName .' => '. $$targetVarName . "\n";
}

这将输出如下内容:

item1 => aaa
item2 => bbb
item3 => ccc
item4 => ddd
item5 => 333

【讨论】:

  • 干杯!如果它有帮助,请不要忘记接受它作为答案:)
猜你喜欢
  • 2017-12-25
  • 2022-01-11
  • 2016-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-21
  • 2020-04-22
相关资源
最近更新 更多