Reputation: 301
I've this multidimensional array in PHP:
Array
(
[0] => Array
(
[continent] => Europa
[country] => France
[capital] => Paris
)
[1] => Array
(
[continent] => Europa
[country] => Spain
[capital] => Madrid
)
[2] => Array
(
[continent] => Asia
[country] => Russia
[capital] => Moscow
)
)
How can I group countries depending the continent ?
So countries in the same continent should be group together.
The desired output should be:
Array
(
[Europa] => Array
(
[country] => France
[capital] => Paris
),
(
[country] => Spain
[capital] => Madrid
)
[Asia] => Array
(
[country] => Russia
[capital] => Moscow
)
)
How it is possible with PHP please ?
Thanks.
Upvotes: 1
Views: 225
Reputation: 49208
$groupByContinent = function(array $list) {
return array_reduce($list, function($grouped, $item) {
$grouped[$item['continent']][] = $item;
return $grouped;
}, []);
};
$groupedByContinent = $groupByContinent($data);
Or:
$groupByProperty = function(array $list, string $property) {
return array_reduce($list, function($grouped, $item) use(&$property) {
$grouped[$item[$property]][] = $item;
return $grouped;
}, []);
};
$groupedByContinent = $groupByProperty($data, 'continent');
Upvotes: 1
Reputation: 42093
You can also try:
$data = array(
array(
"continent" => "Europa",
"country" => "France",
"capital" => "Paris",
),
array(
"continent" => "Europa",
"country" => "Spain",
"capital" => "Madrid",
),
array(
"continent" => "Asia",
"country" => "Russia",
"capital" => "Moscow",
)
);
$group_by = 'continent';
$attributes = array( 'country', 'capital' );
$output = array();
foreach( $data as $country ) {
if( isset( $country[$group_by] ) ) {
$one = array();
foreach( $attributes as $attribute ) {
if( isset( $country[$attribute] ) ) {
$one[$attribute] = $country[$attribute];
}
}
$output[ $country[$group_by] ][] = $one;
}
}
print_r($output);
Upvotes: 0
Reputation: 1435
You can create a new array variable, loop through your data array checking to see if the key has already been created and if not, create it and add the related data to that key.
<?php
// $data: the name of your array
$grouped_data = array();
for ($i = 0; $i < count($data); $i++) {
$key = $data[$i]['continent'];
if (!isset($grouped_data[$key])) {
$grouped_data[$key] = array();
}
$grouped_data[$key][] = array(
'country' => $data[$i]['country'],
'capital' => $data[$i]['capital']
);
}
?>
Upvotes: 1