Skip to content

Instantly share code, notes, and snippets.

@grekodev
Last active October 30, 2019 23:08
Show Gist options
  • Save grekodev/20f7f753879d2ed2b1af93ed22a0708c to your computer and use it in GitHub Desktop.
Save grekodev/20f7f753879d2ed2b1af93ed22a0708c to your computer and use it in GitHub Desktop.
functions group arrays php awesome :)
$original = array
(
array
(
"dni" => 98989898,
"email" => "edgra@gmail.com",
"date" => "2016-09-02 20:58:53",
"items" => 7
),
array
(
"dni" => 9874569,
"email" => "reyna@gmail.com",
"date" => "2016-09-02 20:58:54",
"items" => 1
),
array
(
"dni" => 44520253,
"email" => "llavilla10@gmail.com",
"date" => "2016-09-02 20:18:12",
"items" => 1,
),
array
(
"dni" => 44520253,
"email" => "cesar@test.com",
"date" => "2016-09-02 20:18:05",
"items" => 2
),
print_r(_group_by($original, 'dni'));
print_r(groupArray($original, 'dni'));
print_r(groupsArrays($original, 'dni', ['items'=>array('items')], ['dni','date','email']));
function _group_by($array, $key) {
$return = array();
foreach($array as $val) {
$return[$val[$key]][] = $val;
}
return $return;
}
function groupArray($array, $groupkey)
{
if (count($array) > 0) {
$keys = array_keys($array[0]);
$removekey = array_search($groupkey, $keys);
if ($removekey === false)
return array("Clave \"$groupkey\" no existe");
else
unset($keys[$removekey]);
$groupcriteria = array();
$return = array();
foreach ($array as $value) {
$item = null;
foreach ($keys as $key) {
$item[$key] = $value[$key];
}
$busca = array_search($value[$groupkey], $groupcriteria);
if ($busca === false) {
$groupcriteria[] = $value[$groupkey];
$return[] = array($groupkey => $value[$groupkey], 'groupeddata' => array());
$busca = count($return) - 1;
}
$return[$busca]['groupeddata'][] = $item;
}
return $return;
} else
return array();
}
function groupsArrays($array,$indexUnique,$assoGroup,$keepInOne){
$retour = array();
$id = $array[0][$indexUnique];
foreach ($keepInOne as $keep){
$retour[$id][$keep] = $array[0][$keep];
}
foreach ($assoGroup as $cle=>$arrayKey){
$arrayGrouped = array();
foreach ($array as $data){
if($data[$indexUnique] != $id){
$id = $data[$indexUnique];
foreach ($keepInOne as $keep){
$retour[$id][$keep] = $data[$keep];
}
}
foreach ($arrayKey as $val){
$arrayGrouped[$val] = $data[$val];
}
$retour[$id][$cle][] = $arrayGrouped;
$retour[$id][$cle] = array_unique($retour[$id][$cle],SORT_REGULAR);
}
}
return $retour;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment