I am working with mysql and Php,and i am getting data in following format
Array
(
[country] => India
[total] => 23
)
Array
(
[country] => USA
[total] => 1
)
Array
(
[country] => Japan
[total] => 1
)
I just want that if total match of any countries then should get in same array like following format
Array
(
[country] => India
[total] => 23
)
Array
(
[country] => USA,Japan
[total] => 1
)
Here is my mysql query
SELECT country,COUNT(*) as total FROM doctors GROUP BY country ORDER BY COUNT(*) DESC
Here is my code
<?php foreach ($data as $total) {
echo "<pre>";print_R($total);
?>
<p><?php echo $total['country']; ?><?php echo $total['total']; ?></p>
<?php } ?>
$countriesByTotal = [];
foreach ($data as $row) {
$countriesByTotal[$row['total']][] = $row['country'];
}
foreach ($countriesByTotal as $total => $countries) {
$countriesByTotal[$total] = [
'country' => implode($countries, ','),
'total' => $total
];
}
$countriesByTotal = array_values($countriesByTotal); // optional
print_r($countriesByTotal);
Result:
Array
(
[0] => Array
(
[country] => India
[total] => 23
)
[1] => Array
(
[country] => USA,Japan
[total] => 1
)
)
rextester-demo
Another way is just to change your SQL query using GROUP_CONCAT():
SELECT total, GROUP_CONCAT(country) as country
FROM (SELECT country,COUNT(*) as total FROM doctors GROUP BY country) sub
GROUP BY total
ORDER BY total DESC
array_walk() can be used to concat the country of the same total count.
$data = [];
array_walk($array, function ($value) use (&$data) {
$data[$value['total']] = isset($data[$value['total']])
? ['country' => "{$data[$value['total']]['country']},{$value['country']}", 'total' => $value['total']]
: $value;
});
print '<pre>';
print_r($data);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With