不确定在这种情况下我是否可以使用array_incross或array_search


Not sure if I can use array_intersect or array_search in this case

我有一个数组($entry),它可以有两组密钥中的任何一组:

"custom_0_first" AND "custom_0_last";

"custom_1_first" AND "custom_1_last";

我正在尝试做以下操作,但它似乎没有设置变量:

$firstname = array_search('custom_0_first', $entry) || array_search('custom_1_first', $entry);
$lastname = array_search('custom_0_last', $entry) || array_search('custom_1_last', $entry);

请注意,$entry['custom_0_first']确实可以正常工作。我试图避免在这里发表IF声明。

我对array_search或PHP如何工作的理解是否不正确?据我所知,如果第一个array_search没有找到键,函数将返回FALSE,然后它将检查OR语句的右侧。这不正确吗?我看到了array_intersect,我认为它可能有效,但它似乎不适用于具有关联键的数组。

您可以使用array_entersect_key来获取您要查找的值。它返回一个数组。您可以使用reset获得结果数组的第一个(理论上唯一的)元素。它将给出一个严格的标准通知"只有变量应该通过引用传递",但它会起作用。

$first = reset(array_intersect_key($entry, ['custom_0_first' => 0, 'custom_1_first' => 0]));
$last = reset(array_intersect_key($entry, ['custom_0_last' => 0, 'custom_1_last' => 0]));

另一种方法是使用isset检查密钥。

$first = isset($entry['custom_0_first']) ? $entry['custom_0_first'] : $entry['custom_1_first'];
$last = isset($entry['custom_0_last']) ? $entry['custom_0_last'] : $entry['custom_1_last'];

与JavaScript不同,||运算符总是返回布尔值。将其替换为?:运算符。

$a ?: $b实际上是$a ? $a : $b的短语法,参见三元运算符:

如果expr1的求值结果为TRUE,则表达式(expr1) ? (expr2) : (expr3)的求值结果是expr2,如果expr1的求值结果却是FALSE,则表达式为expr3

从PHP 5.3开始,可以省略三元运算符的中间部分。如果expr1计算为TRUE,则表达式expr1 ?: expr3返回expr1,否则返回expr3