PHP中如果array_key_exists,则变量等于数组值:如何实现?

3
我将两个数组合并后创建了以下数组,名为$group_wages_array:
Array ( [1] => 500 [4] => 44 [6] => 80 [3] => 11.25 )

我想测试数组键是否匹配X,如果匹配,将一个变量设置为它的值。以下是我的代码:

注意:整个代码块在while循环中执行,因此$thegroup ['group_id']的值将发生变化。为了举例,我将其值设置为“6”。

$thegroup['group_id'] = "6" // This particular group (for simplicity)

if (array_key_exists($thegroup['group_id'], $group_wages_array)) {

    $this_wages = // Need this to be 80... how do I do it?

}

那么,我应该如何让$this_wages等于键值?

应该可以运行。如果不行,尝试将 $thegroup['group_id'] 强制转换为整数。 - BoltClock
只要 PHP 可以将其强制转换为字符串或整数,您可以使用任何内容作为数组键。这包括在另一个数组引用中嵌入一个数组引用:$outer[$inner[1]],因此 $group_wages_array[$thegroup['group_id']] 也是可以的。 - Marc B
+1 鼓励详细说明变量的含义和使用方式,而不是仅仅抛出缺乏上下文的代码。希望更多人能够这样做。 - Herbert
2个回答

8
你只需要使用数组中的键来获取它:
$thegroup['group_id'] = "6" // This particular group (for simplicity)

if (array_key_exists($thegroup['group_id'], $group_wages_array)) {
    $this_wages = $group_wages_array[$thegroup['group_id']];
}

此外,数组键不是0、1、2等,因为您在Array ( [1] => 500 [4] => 44 [6] => 80 [3] => 11.25 )中明确设置了它们。


1
你正在尝试做的是:
$group_wages_array[6];

而且

$thegroup['group_id'] = 6;

你可以把这个作为键。

if (array_key_exists($thegroup['group_id'], $group_wages_array)) {
    $this_wages = $group_wages_array[$thegroup['group_id']];   
}

好的,当我使用双括号时它可以工作:$this_wages = $combined_group_wages[$thegroup['group_id']]; - Oseer
你说得对,那是一个语法错误,现在应该正确了。谢谢你指出来。 - Gazler

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接