【问题标题】:How to find a key of array whose elements match elements of other array如何找到其元素与其他数组的元素匹配的数组的键
【发布时间】:2017-01-24 15:37:28
【问题描述】:

我有一个这样的数组$shraniKastomFildove

array(4) { [0]=> string(12) "hashed_token" [1]=> string(17) "registration_time" [2]=> string(12) "noviCustmDev" [3]=> string(2) "no" }

还有一个像这样的数组$namesOfCustomFieldsUserWatsToUpdate

array(1) { [0]=> string(12) "noviCustmDev" }

我想在$shraniKastomFildove 中找到匹配元素的索引。在这种情况下,它将是 2,因为存储了具有“noviCustmDev”值的 2 个元素的索引。

这是我尝试获取它的方法:

foreach($namesOfCustomFieldsUserWatsToUpdate as $nesto){
    foreach($shraniKastomFildove as $dF){
       if($dF==$nesto){
           var_dump(key($shraniKastomFildove));
       }
     }
 }

但是这里它转储了数字 3。我想知道是否有更好、更有效的方法来获得准确的值,在这种情况下为 2,或者是由于 key() 计数索引为 1 而不是从 0?

【问题讨论】:

标签: php arrays


【解决方案1】:

您可以使用array_search 函数在数组中搜索值。

如果在数组中找到needle的key,则该方法返回,否则返回FALSE

所以你的代码会是这样的:

foreach($namesOfCustomFieldsUserWatsToUpdate as $nesto){
    $key = array_search($nesto, $shraniKastomFildove);
    var_dump($key);
 }

【讨论】:

  • 太棒了,解决了。我已经自己尝试了 array_search 但由于某种原因它没有按预期工作
猜你喜欢
  • 2015-05-23
  • 2013-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多