如何构建包含大量具有相同名称模式的变量的表达式?

问题描述 投票:0回答:1

我的系统脚本中有 50 个变量。 都有相同的命名方式,例如:

$case_un
$case_deux
$case_trois
...
$case_fourthy

我需要用所有这些构建一个表达式,而无需编写 50 个变量名称的代码!

由于我所有变量的名称都以模式“case_”开头,是否有语法来对它们或其他表达式求和?

我需要做这样的事情:

   $test_of_cases = $case_un && $case_deux && $case_trois && ...........$case_fourthy ;

还有那个东西:

  $total_of_sums = $sum_un + $sum_deux + ............$sum_fifthy ;

那么,有没有办法用 PHP 编写代码? 在正式语言中,我只需要对名称以 'case_' 开头的所有变量求和。

我的 50 个变量无法存储在数组中,因为它们来自不同的来源和表达式结果。

我不确定,但我觉得有一种表达可以用其他语言来表达:

    LET a=SUM (`*case_*`)
    LET b=XOR (`*case_*`)
    LET c=AND (`*case_*`)

我在30年前的旧研究中了解到.....

我希望 PHP 也能做同样的事情,否则不行,我必须写 50 行代码!

致以诚挚的问候

php variables design-patterns let
1个回答
0
投票

假设你有这样一个数组

$arr = [
    'people_physic_eyes' => 1,
    'people_physic_weight' => 2,
    ...
    'name' => 'james',
    'age' => 15,
    ...
];

你想对键名以“people_physic_”开头的所有值求和,有很多方法可以实现,这里是一个例子,使用

array_reduce

$sum = array_reduce(
    array_keys($arr),
    function ($sum, $key) use ($arr) {
        # if the key starts with 'people_physic_', sum up the value
        return strpos($key, 'people_physic_') === 0 ? $sum + $arr[$key] : $sum;
    },
    0
);

但这效率不高,因为您必须在每次调用时比较所有键。

© www.soinside.com 2019 - 2024. All rights reserved.