【问题标题】:Not sure if I can use array_intersect or array_search in this case不确定在这种情况下我是否可以使用 array_intersect 或 array_search
【发布时间】:2015-06-30 18:34:41
【问题描述】:

我有一个数组 ($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,我认为它可能有效,但它似乎不适用于具有关联键的数组。

【问题讨论】:

  • 请显示 var_dump($entry)
  • array_search() 找到值,而不是键
  • @splash58 是的,我想要的是值,而不是键。如果键存在,我想要属于custom_0_first 的值,否则属于custom_1_first 的值
  • 可能我理解的不正确,但是如果'custom_0_first''custom_0_last'等可能是$entrykeys,那么array_search()就找不到了他们。
  • @Don'tPanic 你是对的。我误解了array_search。我虽然它正在搜索一个键,如果找到该键,将返回它的值。看起来我要回到过去的 isset?:

标签: php arrays if-statement operators


【解决方案1】:

您可以使用 array_intersect_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'];

【讨论】:

  • 我试图做一些比三元更简洁和优雅的东西,但我想我会采用简单的解决方案。 :) 谢谢。
  • @Armstrongest 并不是说​​它现在对我们大多数人很有用,但是在 PHP 7 中我们将有 ?? 来处理这些事情。很酷。 :)
  • 是的,我在 C# 中使用了空合并运算符,因为它是在 C# 2.0 中引入的。这是我关于 SO 最受欢迎的问题之一。很高兴看到它来到 PHP,当然!
【解决方案2】:

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

$a ?: $b 实际上是$a ? $a : $b 的简短语法,请参阅ternary operator

如果expr1 计算为TRUE,则表达式(expr1) ? (expr2) : (expr3) 计算为expr2,如果expr1 计算为FALSE,则expr3

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

【讨论】:

  • 这就是让我陷入困境的原因。谢谢。我又在想javascript了。
  • 我应该可以使用:$firstname = array_search('custom_0_first', $entry) ?: array_search('custom_1_first', $entry);,对吧?我要测试一下。
  • 我刚刚意识到我理解 array_search 不正确,因为它搜索的是值,而不是键名。哦!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-10
  • 2012-03-28
  • 2021-07-09
  • 2019-12-15
  • 2016-09-12
  • 2016-11-07
相关资源
最近更新 更多