I need help with how to remove the duplication within list of countries based on country_id.
I have a table which includes many projects for a country and counting the projects number which is working fine but need to print without duplication, only one country_id with the count of its project.
The code has been added - if anyone can help it is appreciated
<table>
<tr>
<th>Country ID</th>
<th>Country Name</th>
<th>Number of Place</th>
</tr>
<?php
$country_counts = [];
foreach ($projects as $project) {
$country_id = $project['Project']['country_id'];
if (isset($country_counts[$country_id])) {
$country_counts[$country_id] ;
?>
<tr>
<td style="width: 30%"><?php echo $project['Project']['country_id']; ?></td>
<td style="width: 30%"><?php echo 'Country Name'; ?></td>
<td style="width: 30%"><?php echo $country_counts[$project['Project']['country_id']]; ?></td>
</tr>
<?php
} else {
$country_counts[$country_id] = 1;
}
}
?>
</table>
the result which i got is shows the result
CodePudding user response:
Do something like this
$checkout_array = array_unique($checkout_array, SORT_REGULAR);
I did this for my own you can do it for your array
CodePudding user response:
I am unable to test this code but the idea of what I suggested as the second options goes as follows:
<table>
<tr>
<th>Country ID</th>
<th>Country Name</th>
<th>Number of Place</th>
</tr>
<?php
$country_counts=[];
$ids=array();// Store unique country_id values here
foreach( $projects as $project ) {
$country_id = $project['Project']['country_id'];
# Check if the country_id is NOT in the array and display if OK.
if( isset( $country_counts[ $country_id ] ) && !in_array( $country_id, $ids ) ) {
$country_counts[$country_id] ;
?>
<tr>
<td style="width: 30%"><?php echo $project['Project']['country_id']; ?></td>
<td style="width: 30%"><?php echo 'Country Name'; ?></td>
<td style="width: 30%"><?php echo $country_counts[$project['Project']['country_id']]; ?></td>
</tr>
<?php
// add the country_ID to the array so that
// on the next iteration of the loop the $ids
// array will be checked again and no output if
// it is already in the array.
$ids[]=$country_id;
} else {
$country_counts[$country_id] = 1;
}
}
?>
</table>