Try this I kept it as simple as I could since you are a beginner. First we take the unique spec types by using array_map to take out only spec types and then array_unique for taking out the unique values. After that for every spec id we would want to search the matching spec types and filter them out. For this we use array_filter and then again another array_map to take out the other ids and finally an implode function for converting the array into a string.
$data = [
["OTHER_ID"=>"A", "SPEC_TYPE"=>"1"],
["OTHER_ID"=>"B", "SPEC_TYPE"=>"2"],
["OTHER_ID"=>"C", "SPEC_TYPE"=>"1"],
["OTHER_ID"=>"D", "SPEC_TYPE"=>"3"],
["OTHER_ID"=>"E", "SPEC_TYPE"=>"3"]
];
$result = array_map(function ($a) { return $a["SPEC_TYPE"]; }, $data);
$result = array_unique($result);
$response=[];
foreach($result as $r) {
$response[$r] = array_filter($data, function ($d) use($r) { return $r==$d["SPEC_TYPE"]; });
$response[$r] = implode(array_map(function ($a) { return $a["OTHER_ID"]; }, $response[$r]), ", ");
}
echo json_encode($response);
// {"1":"A, C","2":"B","3":"D, E"};
In laravel you have helper functions to reduce the unnecessary code so we can reduce our array_map with array_pluck. Also array_where could be used in place of array_filter but in this case it would have the same callback and functionality so let's keep the filter for now. Below code isn't tested but should do the thing.
$result = array_pluck($data, "SPEC_TYPE");
$result = array_unique($result);
$response=[];
foreach($result as $r) {
$response[$r] = array_filter($data, function ($d) use($r) { return $r==$d["SPEC_TYPE"]; });
$response[$r] = implode(array_pluck($response[$r], "OTHER_ID"), ", ");
}
Resources to study more on this:
Laravel helper functions: https://laravel.com/docs/5.0/helpers
PHP array functions: https://www.w3schools.com/php/php_ref_array.asp