PHP 8.5.0 Alpha 4 available for testing

Voting

: five plus zero?
(Example: nine)

The Note You're Voting On

g8z at yahoo dot com
19 years ago
<?php
/**
This sort function allows you to sort an associative array while "sticking" some fields.

$sticky_fields = an array of fields that should not be re-sorted. This is a method of achieving sub-sorts within contiguous groups of records that have common data in some fields.

Courtesy of the $5 Script Archive: http://www.tufat.com
**/

define( 'ASC_AZ', 1000 );
define( 'DESC_AZ', 1001 );
define( 'ASC_NUM', 1002 );
define( 'DESC_NUM', 1003 );

function
stickysort( $arr, $field, $sort_type, $sticky_fields = array() ) {
$i = 0;
foreach (
$arr as $value) {
$is_contiguous = true;
if(!empty(
$grouped_arr)) {
$last_value = end($grouped_arr[$i]);

if(!(
$sticky_fields == array())) {
foreach (
$sticky_fields as $sticky_field) {
if (
$value[$sticky_field] <> $last_value[$sticky_field]) {
$is_contiguous = false;
break;
}
}
}
}
if (
$is_contiguous)
$grouped_arr[$i][] = $value;
else
$grouped_arr[++$i][] = $value;
}
$code = '';
switch(
$sort_type) {
case
ASC_AZ:
$code .= 'return strcasecmp($a["'.$field.'"], $b["'.$field.'"]);';
break;
case
DESC_AZ:
$code .= 'return (-1*strcasecmp($a["'.$field.'"], $b["'.$field.'"]));';
break;
case
ASC_NUM:
$code .= 'return ($a["'.$field.'"] - $b["'.$field.'"]);';
break;
case
DESC_NUM:
$code .= 'return ($b["'.$field.'"] - $a["'.$field.'"]);';
break;
}

$compare = create_function('$a, $b', $code);

foreach(
$grouped_arr as $grouped_arr_key=>$grouped_arr_value)
usort ( $grouped_arr[$grouped_arr_key], $compare );

$arr = array();
foreach(
$grouped_arr as $grouped_arr_key=>$grouped_arr_value)
foreach(
$grouped_arr[$grouped_arr_key] as $grouped_arr_arr_key=>$grouped_arr_arr_value)
$arr[] = $grouped_arr[$grouped_arr_key][$grouped_arr_arr_key];

return
$arr;
}
?>

<< Back to user notes page

To Top