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

hai*_*ets 6 php foreach loops distinct echo

我有一个foreach循环,它在我的搜索结果中回显了每个属性类型.代码如下:

<?php 
    foreach($search_results as $filter_result) {
        echo $filter_result['property_type'];
    } 
?>
Run Code Online (Sandbox Code Playgroud)

上面的代码返回:

house house house house flat flat flat
Run Code Online (Sandbox Code Playgroud)

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

我想要上面的代码返回:

  • 平面

每次都不要重复每个项目.有任何想法吗??

hsz*_*hsz 17

试试:

$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'];
}
Run Code Online (Sandbox Code Playgroud)


ale*_*ale 6

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
)
Run Code Online (Sandbox Code Playgroud)

您需要稍微更改它以使用property_type数组的一部分进行检查。