I have array $arr :
Array ( [0] => Array ( [id] => 1 [year] => 1999 ) [1] => Array ( [id] => 1 [year] => 2022 ) [2] => Array ( [id] => 2 [year] => 2020 ) [3] => Array ( [id] => 1 [year] => 2020 ) )
and I want to unite equal years and sort ids like that:
"2022" : "1"
"2020" : "1", "2"
"1999" : "1"
How can I do it??? Thanks!
CodePudding user response:
I factored a simple function that takes your array as input and will return a new array grouped by year. Such function just relies on foreach statements without playing too far with callbacks/closures and functional programming.
I included a live example that will show the var_dump of the grouped variable:
https://sandbox.onlinephpfunctions.com/c/20e1f
<?php
//input
$items = [
['id' => 1, 'year' => 1999],
['id' => 1, 'year' => 2022],
['id' => 2, 'year' => 2020],
['id' => 1, 'year' => 2020]
];
$grouped = groupItems($items);
var_dump($grouped);
/**
* Takes your input array as argument
* and returns its items grouped by year
*/
function groupItems($input){
$groupedByYear = [];
//foreach item in input as item
foreach($input as $item)
{
//if the grouped array still doesn't contain this year
if (!array_key_exists($item['year'], $groupedByYear))
//initialize an empty array for this year as a new group
$groupedByYear[$item['year']] = [];
//add this item id to the year group
$groupedByYear[$item['year']][] = $item['id'];
}
//sort children
foreach($groupedByYear as $key => &$value){
sort($value);
}
return $groupedByYear;
}