从PHP中的foreach循环返回不同的值?

问题描述 投票:6回答:6

我有一个foreach循环,echo是我搜索结果中的每个属性类型。代码如下:

<?php 
    foreach($search_results as $filter_result) {
        echo $filter_result['property_type'];
    } 
?>

上面的代码返回:

house house house house flat flat flat

我想做一些类似于MySQL'distinct'的东西,但我不知道如何在foreach语句中做到这一点。

我想要上面的代码返回:

  • 平面

每次都不要重复每个项目。我怎样才能做到这一点?

php loops foreach distinct echo
6个回答
15
投票

试试:

$property_types = array();
foreach($search_results_unique as $filter_result){
    if ( in_array($filter_result['property_type'], $property_types) ) {
        continue;
    }
    $property_types[] = $filter_result['property_type'];
    echo $filter_result['property_type'];
}

4
投票

http://php.net/manual/en/function.array-unique.php

例:

$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input); 
print_r($result);

Array
(
    [a] => green
    [0] => red
    [1] => blue
)

您将需要稍微改变它以检查使用数组的property_type部分。


0
投票

我在这里使用两个循环。一个用于构建不同property_type字段的数组(您可以使用循环中的代码来检查项目尚不存在)。

然后,使用第二个循环来遍历数组,并使用echo项目列表。


0
投票

您必须跟踪已回显的值或构建所有$ filter_result ['property_type']的值的新唯一数组。但那将需要您再次迭代该阵列以实际打印。所以保持跟踪会更好。


0
投票

我当时认为in_array()函数有一些参数来获取找到的项目的数量。

但是不存在。

所以试试array_unique()

更好的方法是在foreach循环之前复制数组并应用此函数。


-1
投票
<?php 

$filter=array();
foreach($search_results as $filter_result)
   $filter[]=$filter_result['property_type'];
$filter=array_unique($filter);

print_r($filter);
?>
© www.soinside.com 2019 - 2024. All rights reserved.