How to search Array for multiple values in PHP?

后端 未结 5 1316
滥情空心
滥情空心 2020-12-03 13:58

I need to get the keys from values that are duplicates. I tried to use array_search and that worked fine, BUT I only got the first value as a hit.

I need to get both

5条回答
  •  一个人的身影
    2020-12-03 14:09

    You want array_keys with the search value

    array_keys($list[0], "2009-09-09");
    

    which will return an array of the keys with the specified value, in your case [0, 2]. If you want to find the duplicates as well, you can first make a pass with array_unique, then iterate over that array using array_keys on the original; anything which returns an array of length > 1 is a duplicate, and the result is the keys in which the duplicates are stored. Something like...

    $uniqueKeys = array_unique($list[0])
    
    foreach ($uniqueKeys as $uniqueKey)
    {
      $v = array_keys($list[0], $uniqueKey);
    
      if (count($v) > 1)
      {
        foreach ($v as $key)
        {
          // Work with $list[0][$key]
        }
    
      }
    }
    

提交回复
热议问题