count rows in foreach based on value

491 Views Asked by At

Good day all, I need help in project table I have a table called projects and i want to count the projects based on country_id column using php in a foreach... ist possible? however i am using cakephp the old version 1.2 ...

I tried this code:

<table>
    <tr>
        <th>Country </th>
        <th>Country Name</th>
        <th>Number of Place</th>
    </tr>

    <?php 
    $count_country =0;
    $country_count_each=0;
    foreach ($projects as $project){ 
        $country_count_each = $project['Project']['country_id'];
        if($project['Project']['country_id']==$country_count_each){
            $count_country+=$country_count_each;
    
?>
    <tr>
        <td style="width: 30%"><?php echo $project['Project']['country_id']; ?></td>
        <td style="width: 30%"><?php echo 'Country Name'.$tt; ?></td>
        <td style="width: 30%"><?php echo $count_country; ?></td>
    </tr>
<?php 
        } 
    }
    ?>

</table>

Project Table

1

There are 1 best solutions below

2
Barmar On BEST ANSWER

You need to loop over the entire array and get all the counts first. You can put them into an associative array:

$country_counts = [];
foreach ($projects as $project) {
    $country = $project['Project']['country_id'];
    if (isset($country_counts[$country])) {
        $country_counts[$country]++;
    } else {
        $country_counts[$country] = 1;
    }
}

?>
<table>
    <tr>
        <th>Country </th>
        <th>Country Name</th>
        <th>Number of Place</th>
    </tr>

    <?php 
    foreach ($projects as $project) {
    ?>
        <tr>
            <td style="width: 30%"><?php echo $project['Project']['country_id']; ?></td>
            <td style="width: 30%"><?php echo 'Country Name'.$tt; ?></td>
            <td style="width: 30%"><?php echo $country_counts[$project['Project']['country_id']]; ?></td>
        </tr>  
    <?php 
    } 
?>

</table>