note 57006 deleted from function.array-unique by sobak

From: Date: Sun, 11 Dec 2016 06:54:53 +0000
Subject: note 57006 deleted from function.array-unique by sobak
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-208484@lists.php.net to get a copy of this message
Note Submitter: passtschu AT freenet DOT de ---- array_unique for multidimensional arrays. similar to the DISTINCT in SQL function. the function can group, sum and count keys <?PHP /* $array - nothing to say $group_keys - columns which have to be grouped - can be STRING or ARRAY (STRING, STRING[, ...]) $sum_keys - columns which have to be summed - can be STRING or ARRAY (STRING, STRING[, ...]) $count_key - must be STRING - count the grouped keys */ function array_distinct ($array, $group_keys, $sum_keys = NULL, $count_key = NULL){ if (!is_array ($group_keys)) $group_keys = array ($group_keys); if (!is_array ($sum_keys)) $sum_keys = array ($sum_keys); $existing_sub_keys = array (); $output = array (); foreach ($array as $key => $sub_array){ $puffer = NULL; #group keys foreach ($group_keys as $group_key){ $puffer .= $sub_array[$group_key]; } $puffer = serialize ($puffer); if (!in_array ($puffer, $existing_sub_keys)){ $existing_sub_keys[$key] = $puffer; $output[$key] = $sub_array; } else{ $puffer = array_search ($puffer, $existing_sub_keys); #sum keys foreach ($sum_keys as $sum_key){ if (is_string ($sum_key)) $output[$puffer][$sum_key] += $sub_array[$sum_key]; } #count grouped keys if (!array_key_exists ($count_key, $output[$puffer])) $output[$puffer][$count_key] = 1; if (is_string ($count_key)) $output[$puffer][$count_key]++; } } return $output; } ?>

« previous php.notes (#208484) next »