varad mayee varad mayee - 7 months ago 14
PHP Question

Compare Same Array and return results

$arr1 = array(
array
(
'id' => '1',
'city' => 'A.bad',
),
array
(
'id' => '2',
'city' => 'Pune',
),
array
(
'id' => '1',
'city' => 'Mumbai',
)
);


and i have to compare the this by id and i want the output like below
I am working on a project and i am stuck on this my question is i have one array which is like below

$result = array(
array(
'id'='1',
'city'='A.bad','Mumbai'
),
array(
'id'='2',
'city'='Pune'
)
);


if we have same id as in the first one is a.bad so it will take it and in the third one it has id 1 and city as mumbai so it will combine as id 1 and city as a.bad,mumbai and other records are filtered in same manner

Answer

Loop through the array and generate a new array depending on the id.You can try this -

$new = array();
foreach($arr1 as $array) {
    $new[$array['id']]['id']= $array['id'];
    // check if the city value set for that id
    // if set the concatenate else set with the city name 
    $new[$array['id']]['city']= (isset( $new[$array['id']]['city'])) ?  ($new[$array['id']]['city'] . ',' . $array['city']) : $array['city'];
}

Fiddle

If you are getting that data from database the you can group them in the query also.