Search code examples
phparraysmultidimensional-arraycountunique

Count unique rows of data based on the values in two columns


I have a multidimensional array like below and I want to create another array which shows the unique number of users per city.

Array
(
    [0] => Array
        (
            [id] => 1
            [city] => Melbourne
            [date_added] => 1435852550
            [user_name] => user_1
        )

    [1] => Array
        (
            [id] => 2
            [city] => Melbourne
            [date_added] => 1435852550
            [user_name] => user_1
        )

    [2] => Array
        (
            [id] => 3
            [city] => Sydeny
            [date_added] => 1435852550
            [user_name] => user_2
        )

    [3] => Array
        (
            [id] => 4
            [city] => Perth
            [date_added] => 1435852550
            [user_name] => user_3
        )
    [4] => Array
        (
            [id] => 5
            [city] => Perth
            [date_added] => 1435852550
            [user_name] => user_4
        )
)

What I am trying to get is the unique number of users per city like the below:

Array
(
    [Melbourne] => 1
    [Sydeny] => 1
    [Perth] => 2
)

Solution

  • use the city as index, and array user_names array as value, then map the value to lentgth of the value.

    foreach($array as $v)
    {
      $temp[$v['city']][$v['user_name']] = 1;
    }
    $result = array_map(function($v){return count($v);}, $temp);