Get the keys for duplicate values in an array

前端 未结 9 1576
温柔的废话
温柔的废话 2020-11-28 11:11

I have the following array:

$myarray = Array(\"2011-06-21\", \"2011-06-22\", \"2011-06-22\", \"2011-06-23\", \"2011-06-23\", \"2011-06-24\", \"2011-06-24\",         


        
9条回答
  •  天命终不由人
    2020-11-28 11:26

    I really like Francois answer, here is something I came up with that preserves keys. I'll answer the first question first:

    $array = array('2011-06-21', '2011-06-22', '2011-06-22');
    /**
     * flip an array like array_flip but
     * preserving multiple keys per an array value
     * 
     * @param array $a
     * @return array
     */
    function array_flip_multiple(array $a) {
        $result = array();
        foreach($a as $k=>$v)
            $result[$v][]=$k
            ;
        return $result;
    }
    
    $hash = array_flip_multiple($array);
    
    // filter $hash based on your specs (2 or more)
    $hash = array_filter($hash, function($items) {return count($items) > 1;});
    
    // get all remaining keys
    $keys = array_reduce($hash, 'array_merge', array());
    
    var_dump($array, $hash, $keys);
    

    output is:

    # original array
    array(3) {
      [0]=>
      string(10) "2011-06-21"
      [1]=>
      string(10) "2011-06-22"
      [2]=>
      string(10) "2011-06-22"
    }
    
    # hash (filtered)
    array(1) {
      ["2011-06-22"]=>
      array(2) {
        [0]=>
        int(1)
        [1]=>
        int(2)
      }
    }
    
    # the keys
    array(2) {
      [0]=>
      int(1)
      [1]=>
      int(2)
    }
    

    So now the second question:

    Just use the $hash to obtain the keys for the value:

    var_dump($hash['2011-06-22']); returns the keys.

    Benefit is, if you need to check multiple values, data is already stored in the hash and available for use.

提交回复
热议问题