Skip to content

Instantly share code, notes, and snippets.

@hatamiarash7
Last active May 22, 2019 06:03
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 hatamiarash7/6df79117c93f59f7f624aabc70249637 to your computer and use it in GitHub Desktop.
Save hatamiarash7/6df79117c93f59f7f624aabc70249637 to your computer and use it in GitHub Desktop.
PHP group array items by key

Groups an array into another array by a given $key

function array_group(array $array, $key)
{
    $result = [];

    foreach ($array as $item) {
        $column = $item[$by_column];
        unset($item[$by_column]);
        if (isset($result[$column])) {
            $result[$column][] = $item;
        } else {
            $result[$column] = array($item);
        }
    }

    return $result;
}

Example :

$array = $this->array_group($array, 'created_at');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment