Mabro Chickenz
Mabro Chickenz

Reputation: 185

How to remove duplicate in array

I want to show bandwidth usage per month,
there are 2 users who both logged in on June
here is my code :

<?php foreach ($data as $row):

            $date = $row['acctstarttime'];
            $d = date_parse_from_format("Y-m-d", $date);

             $monthNum  = $d["month"];
             $dateObj   = DateTime::createFromFormat('!m', $monthNum);
             $monthName = $dateObj->format('F');                
                        ?>

                <td><?php echo $monthName;?></td>
                </tr>
<?php endforeach;?>

The Output is :
- June
- June
- July

The output I need :
- June
- July

I tried to change my query to :

Function showData() 
    { 

    $this->db->distinct('radacct.acctstarttime'); 
    $this->db->from('radacct');
    $this->db->where('radacct.acctstarttime','y-06-d-h');
    $query = $this->db->get();


    If ($query->num_rows()>0) 
    { 
      Return $query->result(); 
    } 
    Else 
    { 
     Return array(); 
    } 
 }

But it changes nothing (Is my query wrong ?)

I also tried : foreach (array_unique($data) as $row)

But it removes the July

the output of <?php print_r($row['acctstarttime'])?>
is : 2017-06-08 04:12:00 2017-06-08 04:12:00 2017-07-12 05:00:00

Upvotes: 3

Views: 89

Answers (1)

Alessandro Minoccheri
Alessandro Minoccheri

Reputation: 35973

try this:

    <?php 
    $month = [];
    foreach ($data as $row):
        if(!in_array($d["month"], $month)) {
            $month[] = $d['month'];
            $date = $row['acctstarttime'];
            $d = date_parse_from_format("Y-m-d", $date);

            $monthNum  = $d["month"];
            $dateObj   = DateTime::createFromFormat('!m', $monthNum);
            $monthName = $dateObj->format('F');                
            ?>

            <td><?php echo $monthName;?></td>
            </tr>

            <?php 
        }
     endforeach;
  ?>

UPDATE:

    $month = array(); 
    foreach ($data as $row):
       $date = $row['acctstarttime'];
       $d = date_parse_from_format("Y-m-d", $date);
       $monthNum  = $d["month"];
       $dateObj   = DateTime::createFromFormat('!m', $monthNum);
       $monthName = $dateObj->format('F');  
       if(!in_array($monthName, $month)) {
            $month[] = $monthName;
            echo $monthName;
       }
     endforeach;

Upvotes: 2

Related Questions