Returning distinct values from foreach loop in PHP

2020-07-09 02:41发布

I have a foreach loop which echo's each of the property types in my search results. The code is as follows:

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

The above code returns:

house house house house flat flat flat

I would like to do something similar to the MySQL 'distinct', but I am not sure how to do it on a foreach statement.

I want the above code to return:

  • house
  • flat

Not repeat every item each time. How can I do this?

6条回答
时光不老,我们不散
2楼-- · 2020-07-09 03:08

I'd use two loops here. One to build an array of distinct property_type fields (you can use code in the loop to check the item doesn't already exist).

Then, use a second loop to step through the array and echo the list of items.

查看更多
放我归山
3楼-- · 2020-07-09 03:11

I was thinking there was some parameter to the in_array() function to get the count of the items found.

But is doesn't exist.

So try with array_unique().

The better way is to duplicate the array before the foreach loop and apply this function.

查看更多
不美不萌又怎样
4楼-- · 2020-07-09 03:15

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

Example:

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

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

You will need to alter it slightly to check using the property_type part of your array.

查看更多
We Are One
5楼-- · 2020-07-09 03:19

You would have to keep track of already echoed values or build a new unique array of the values of all the $filter_result['property_type']. But that would then require you to iterate over that array once more to actually print. So keeping track would be better.

查看更多
趁早两清
6楼-- · 2020-07-09 03:21

Try with:

$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'];
}
查看更多
▲ chillily
7楼-- · 2020-07-09 03:25
<?php 

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

print_r($filter);
?>
查看更多
登录 后发表回答