Skip to content

Instantly share code, notes, and snippets.

@sonichandni
Created January 24, 2023 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sonichandni/4c5864b8be53ac6aa52eab1f2a5d896c to your computer and use it in GitHub Desktop.
Save sonichandni/4c5864b8be53ac6aa52eab1f2a5d896c to your computer and use it in GitHub Desktop.
php array group by with key value
// Input
$data = array(
array("name" => "John", "age" => 25),
array("name" => "Jane", "age" => 22),
array("name" => "Bob", "age" => 25),
array("name" => "Sara", "age" => 22)
);
$groupedData = array_reduce($data, function($result, $item) {
$result[$item['age']][] = $item;
return $result;
}, array());
// Output
Array
(
[25] => Array
(
[0] => Array
(
[name] => John
[age] => 25
)
[1] => Array
(
[name] => Bob
[age] => 25
)
)
[22] => Array
(
[0] => Array
(
[name] => Jane
[age] => 22
)
[1] => Array
(
[name] => Sara
[age] => 22
)
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment