Created
January 25, 2023 14:10
-
-
Save lov3catch/d13da97f99e2423b454e865192c2fae8 to your computer and use it in GitHub Desktop.
Group array by key
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
$items = [ | |
["id" => 20, "name" => "chimpanzee"], | |
["id" => 40, "name" => "meeting"], | |
["id" => 20, "name" => "dynasty"], | |
["id" => 50, "name" => "chocolate"], | |
["id" => 10, "name" => "bananas"], | |
["id" => 50, "name" => "fantasy"], | |
["id" => 50, "name" => "football"], | |
]; | |
$columnName = "id"; | |
$columnValues = array_values(array_unique(array_column($items, $columnName))); | |
$result = array_combine( | |
$columnValues, | |
array_map( | |
static fn(int $columnValue) => array_values( | |
array_filter( | |
$items, | |
static fn(array $item) => $item[$columnName] === $columnValue | |
) | |
), | |
$columnValues | |
) | |
); | |
ksort($result, SORT_NUMERIC); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment