php - Combine arrays with a common value into a new array -
i working on project , stuck on question have 1 array below
$arr1 = array( array ( 'id' => '1', 'city' => 'a.bad', ), array ( 'id' => '2', 'city' => 'pune', ), array ( 'id' => '1', 'city' => 'mumbai', ) );
and have compare id , want output below.
$result = array( array( 'id'='1', 'city'='a.bad','mumbai' ), array( 'id'='2', 'city'='pune' ) );
if have same id in first 1 a.bad
take , in third 1 has id 1 , city mumbai
combine id 1 , city a.bad
,mumbai
, other records filtered in same manner.
loop through array , generate new array
depending on id
.you can try -
$new = array(); foreach($arr1 $array) { $new[$array['id']]['id']= $array['id']; // check if city value set id // if set concatenate else set city name $new[$array['id']]['city']= (isset( $new[$array['id']]['city'])) ? ($new[$array['id']]['city'] . ',' . $array['city']) : $array['city']; }
if getting data database can group them in query also.
Comments
Post a Comment