How to remove duplicate in an array
I want to show the bandwidth usage per month,
there are 2 users who logged in in 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;?>
Exit:
- June
- June
- July
The result I want is:
- 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 doesn't change anything (is my request wrong?)
I've also tried: foreach (array_unique($data) as $row)
But he removes July
output <?php print_r($row['acctstarttime'])?>
is: 2017-06-08 04:12:00 2017-06-08 04:12:00 2017-07-12 05:00:00
+3
source to share
1 answer
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;
+2
source to share