删除 php 和 cakephp 中 foreach 循环中的重复记录

remove duplication of records in foreach loop in php and cakephp

我需要有关如何删除基于 country_id.

的国家/地区列表中的重复内容的帮助

我有一个 table,其中包括一个国家/地区的许多项目并计算项目数量,它工作正常但需要打印而不重复,只有一个 country_id 及其项目数量。

代码已添加 - 如果有人可以提供帮助,我们将不胜感激

<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>

我得到的结果是 shows the result

做这样的事情

$checkout_array = array_unique($checkout_array, SORT_REGULAR);

我为我自己做的,你可以为你的数组做这个

我无法测试此代码,但我建议的第二个选项的想法如下:

<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>