Skip to content

Instantly share code, notes, and snippets.

@blar
Created February 13, 2014 19:50
Show Gist options
  • Select an option

  • Save blar/8982482 to your computer and use it in GitHub Desktop.

Select an option

Save blar/8982482 to your computer and use it in GitHub Desktop.
<?php
function array_partition($array, $callback, $preserveKeys = false) {
$partitions = array();
foreach($array as $key => $value) {
$partitionName = $callback($value, $key);
if(!array_key_exists($partitionName, $partitions)) {
$partitions[$partitionName] = array();
}
if($preserveKeys) {
$partitions[$partitionName][$key] = $value;
}
else {
$partitions[$partitionName][] = $value;
}
}
return $partitions;
}
$movies = array();
$movies[] = array(
'title' => 'a',
'category' => 'foo'
);
$movies[] = array(
'title' => 'b',
'category' => 'bar'
);
$movies[] = array(
'title' => 'c',
'category' => 'foo'
);
$movies[] = array(
'title' => 'd',
'category' => 'bar'
);
var_dump(array_partition($movies, function($movie) {
return $movie['category'];
}));
array(2) {
["foo"]=>
array(2) {
[0]=>
array(2) {
["title"]=>
string(1) "a"
["category"]=>
string(3) "foo"
}
[1]=>
array(2) {
["title"]=>
string(1) "c"
["category"]=>
string(3) "foo"
}
}
["bar"]=>
array(2) {
[0]=>
array(2) {
["title"]=>
string(1) "b"
["category"]=>
string(3) "bar"
}
[1]=>
array(2) {
["title"]=>
string(1) "d"
["category"]=>
string(3) "bar"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment