我有一个foreach循环,它是我搜索结果中的每个属性类型的echo
。代码如下:
<?php
foreach($search_results as $filter_result) {
echo $filter_result['property_type'];
}
?>
以上代码返回:
house house house house flat flat flat
我想做一些类似MySQL"distinct"的事情,但我不确定如何在foreach语句上做到这一点。
我想返回上面的代码:
- 房屋
- 扁平
不要每次都重复每一项。我该怎么做?
尝试使用:
$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'];
}
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
部分进行检查。
我在这里使用两个循环。一个用于构建不同property_type
字段的数组(您可以在循环中使用代码来检查该项是否已经存在)。
然后,使用第二个循环逐步遍历数组并echo
项目列表。
您必须跟踪已经响应的值,或者为所有$filter_result['property_type']的值构建一个新的唯一数组。但这将需要您再次迭代该数组才能实际打印。所以跟踪会更好。
我认为in_array()函数有一些参数可以获得找到的项的计数。
但它并不存在。
所以试试array_unique()。
更好的方法是在foreach
循环之前复制数组并应用此函数。
<?php
$filter=array();
foreach($search_results as $filter_result)
$filter[]=$filter_result['property_type'];
$filter=array_unique($filter);
print_r($filter);
?>