Count dates inside an array PHP

后端 未结 3 580
盖世英雄少女心
盖世英雄少女心 2021-01-27 07:46

I have this Array :

Array (
[0] => Array ( [x] => 2016-04-19 ) 
[1] => Array ( [x] => 2016-05-25 ) 
[2] => Array ( [x] => 2016-05-26 ) 
[3] =&g         


        
3条回答
  •  再見小時候
    2021-01-27 08:03

    Did you say count only duplicates? Well, you may just loop through the Array of given Dates and bundle the Duplicates into a new array and afterwards get the count of the resulting array like so:

         '2016-04-19',
                "date2"     => '2016-05-25',
                "date3"     => '2016-05-26',
                "date4"     => '2016-05-27',
                "date5"     => '2016-05-28',
                "date6"     => '2016-05-29',   //<== DUPLICATE DATE : 1
                "date7"     => '2016-05-29',   //<== DUPLICATE DATE : 2
                "date8"     => '2016-06-02',
                "date9"     => '2016-06-03',
                "date10"    => '2016-06-07',
                "date11"    => '2016-06-10',
                "date12"    => '2016-06-17',
                "date13"    => '2016-06-24',
                "date14"    => '2016-05-29',   //<== DUPLICATE DATE : 3
                "date15"    => '2016-05-29',   //<== DUPLICATE DATE : 4
            );
    
        // LOOP THROUGH ALL THE GIVEN ARRAYS CHECKING IF ANY OF THEM ALREADY EXIST
        // IF NOT, WE JUST PUSH THE DATE TO $arrHolder ARRAY
        // OTHERWISE WE PERFORM MORE CHECK AND PUSH IT INTO A MULTI-DIMENSIONAL ARRAY: $arrDuplicates.  
        foreach($arrDateList as $key=>$date){
            if(!in_array($date, $arrHolder)){
                $arrHolder[$key]                    = $date;
            }else{
                if(!array_key_exists($date, $arrDuplicates)){
                    // IF THIS KEY EXIST, IT MEANS THAT THIS IS THE 2ND INSTANCE
                    // SO WE ASSIGN A COUNT OF 2 TO IT.
                    $arrDuplicates[$date]           = array($key=>$date, "count"=>2);
                }else{
                    $arrDuplicates[$date]["count"]  =  intval($arrDuplicates[$date]["count"])  + 1;
                }
            }
        }
    
        var_dump($arrDuplicates);
    

    RESULT OF VAR_DUMP

            // YOU CAN SEE THE COUNT (NUMBER OF DUPLICATES)
            // AS WELL AS THE KEY AND EVEN THE DATE.... :-) 
            // NO NEED FOR EXTRA LOGIC THE $arrDuplicates HAS THEM ALL
            // YOU ONLY HAVE TO PEEK IN....         
            array (size=1)
              '2016-05-29' => 
                array (size=2)
                  'date7' => string '2016-05-29' (length=10)
                  'count' => int 4
    

提交回复
热议问题