我有一个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']的值的新唯一数组。但那将需要您再次迭代该阵列以实际打印。所以保持跟踪会更好。
<?php
$filter=array();
foreach($search_results as $filter_result)
$filter[]=$filter_result['property_type'];
$filter=array_unique($filter);
print_r($filter);
?>