note 57006 added to function.array-unique

From: Date: Wed, 21 Sep 2005 14:20:42 +0000
Subject: note 57006 added to function.array-unique
Groups: php.notes 
Request: Send a blank email to php-notes+get-95534@lists.php.net to get a copy of this message
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; } ?> ---- Manual Page -- http://www.php.net/manual/en/function.array-unique.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+57006 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+57006&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+57006&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+57006&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+57006&report=yes&reason=useless Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+57006&report=yes&reason=non-english Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+57006&report=yes&reason=already+in+docs Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+57006&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+57006&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#95534) next »