Re: Multi-Sort -- how to do this?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



tedd wrote:
Hi gang:

Here's the problem. Let's say you have a collection of arrays, such as:

$a = array();
$b = array();
$c = array();
$d = array();

And then you populate the arrays like so:

while(...)
   {
   $a[] = ...
   $b[] = ...
   $c[] = ...
   $d[] = ...
   }

Now, let's say you want to sort the $d array, but you also want the arrays $a, $b, and $c to be arranged in the same resultant order as $d.

For example, please follow this:

Before sort of $d:
$a = [apple, banana, grape, orange]
$b = [100, 2111, 198, 150]
$c = [red, yellow, purple, orange]
$d = [100, 300, 11, 50]

After sort of $d:
$a = [grape, orange, apple, banana]
$b = [198, 150, 100, 2111]
$c = [purple, orange, red, yellow]
$d = [11, 50, 100, 300]

Is there a slick way to do that?

Yes...

<?php

function tedd_sort( &$arrays )
{
    $master = null;
    $followers = array();

    $first = true;
    foreach( array_keys( $arrays ) as $key )
    {
        if( $first )
        {
            $first = false;
            $master = &$arrays[$key];
        }
        else
        {
            $followers[] = &$arrays[$key];
        }
    }


    asort( $master );
    foreach( array_keys( $master ) as $mkey )
    {
        foreach( array_keys( $followers ) as $fkey )
        {
            $value = &$followers[$fkey][$mkey];
            unset( $followers[$fkey][$mkey] );
            $followers[$fkey][$mkey] = &$value;
        }
    }
}

$a = array( 'apple', 'banana', 'grape', 'orange' );
$b = array( 100, 2111, 198, 150 );
$c = array( 'red', 'yellow', 'purple', 'orange' );
$d = array( 100, 300, 11, 50 );

$arrays = array( &$d, &$a, &$b, &$c );
tedd_sort( $arrays );
print_r( $a );
print_r( $b );
print_r( $c );
print_r( $d );

?>

If func_get_args() or func_get_arg() had supported retrieving a reference to the argument, then we could have saved having to pass the arrays via a combined array. I chose to make $d the first array since in your example result set it is the one sorted and thus the rest follow as you would expect.

Cheers,
Rob.
--
http://www.interjinn.com
Application and Templating Framework for PHP

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux