How to extract only different values from an array?

Asked

Viewed 469 times

4

I’m extracting from a array city names. I want to extract cities with different names. In the current case, my script returns several identical city names. I want to recover only once each city name.

The result is this:

Array
(
    [2] => Array
        (
            [Codigo] => 2
            [Cidade] => Porto Alegre
        )

    [3] => Array
        (
            [Codigo] => 3
            [Cidade] => Porto Alegre
        )

    [4] => Array
        (
            [Codigo] => 4
            [Cidade] => Porto Alegre
        )
    ...

The script being used is this:

$cidades = new Imoveis;
$city = $cidades->get_cidades($cidades->key, $cidades->tipo, $cidades->param);

echo "<pre>";
print_r($city);

This script returns me real estate of a Webservice, then the bid would be to return only 1 property from each city or group real estate by cidade.

  • Does code make a difference to you? It’s code of what?

  • I am developing a website from a webservice and wanted to extract the cities to put in a search dropdowm ... http://new.pier36imoveis.com.br/search

1 answer

5

Use array_unique() matching array_column() to extract only the non-repeated key values Cidade.

array_column() is available from php5.5 forward if you are using a previous version, you can use that function to obtain the same result.

<?php

$arr = array(
            array('codigo' => 1, 'cidade' => 'Porto Alegre'),
            array('codigo' => 3, 'cidade' => 'Porto Alegre'),
            array('codigo' => 8, 'cidade' => 'São Paulo'),
            array('codigo' => 9, 'cidade' => 'Rio de Janeiro'),
            array('codigo' => 10, 'cidade' => 'Rio de Janeiro'),
            array('codigo' => 5, 'cidade' => 'Porto Alegre'));


$arr = array_unique(array_column($arr, 'cidade'));

echo '<pre>';
print_r($arr);

Exit:

Array
(
    [0] => Porto Alegre
    [2] => São Paulo
    [3] => Rio de Janeiro
)

Example - phpfiddle

Browser other questions tagged

You are not signed in. Login or sign up in order to post.