Skip to content

Instantly share code, notes, and snippets.

@lov3catch
Created January 25, 2023 14:10
Show Gist options
  • Save lov3catch/d13da97f99e2423b454e865192c2fae8 to your computer and use it in GitHub Desktop.
Save lov3catch/d13da97f99e2423b454e865192c2fae8 to your computer and use it in GitHub Desktop.
Group array by key
<?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