【问题标题】:How to change name of array in PHP using a POST result如何使用 POST 结果更改 PHP 中的数组名称
【发布时间】:2020-07-28 07:39:25
【问题描述】:

假设我有 2 个数组 $test24 和 $test48 。 现在如果我收到一个网络表单 POST $type value 24 我需要执行这个

foreach ($test24 as $val) 
{
code here
}

如果我收到一个网络表单 POST $type value 48 我需要执行此操作

foreach ($test48 as $val) 
{
code here
}

我正在尝试以这种方式在单个 foreach 中聚合/合并上面的代码

foreach ($test$type as $val) 
{
 code here
}

或者这个

foreach ($test.$type as $val) 
{
code here
}

但是这两种解决方案都不起作用,您知道解决方案吗?

【问题讨论】:

    标签: php arrays variables


    【解决方案1】:

    您案例的变量格式为:

    foreach (${'test' . $type} as $val) 
    

    但我建议你使用数组而不是两个变量:

    $test = [24 => [1,2,3], 48 => [4,5,6]];
    
    
    foreach ($test[$type] as $val) {
        echo $val;
    }
    

    【讨论】:

      猜你喜欢
      • 2022-11-21
      • 1970-01-01
      • 2012-06-13
      • 2016-03-05
      • 2015-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多