Jump to content

Custom array sort? asc then desc


Dimensional

Recommended Posts

Any ideas how I could sort this array? I've been trying for a while. Maybe with usort, but I have no idea how...  :shrug:

 

Each entry is laid out like this: ("$status||$id||$shop||$name||$date")

I want it to sort as $status Ascending, and $id Descending.

 

The reason I can't order it from the database to begin with, is because the entries come from more than one database. So ID's go into the array as 4 3 2 1, next database 4 3 2 1, and so on.

Link to comment
Share on other sites

They will look basically like this:

 

0||3 ||words||words||2/18/2010

0||2 ||words||words||2/18/2010

1||1 ||words||words||2/18/2010

0||4 ||words||words||2/18/2010

0||3 ||words||words||2/18/2010

2||2 ||words||words||2/18/2010

2||1 ||words||words||2/18/2010

 

 

It needs to sort by the first number upward. Then within that, the second number downward:

 

0||4 ||words||words||2/18/2010

0||3 ||words||words||2/18/2010

0||3 ||words||words||2/18/2010

0||2 ||words||words||2/18/2010

1||1 ||words||words||2/18/2010

2||2 ||words||words||2/18/2010

2||1 ||words||words||2/18/2010

 

Easy with sql, but I'm not sure how it could be done with an array.

I checked the examples, and didn't see how any of them could work for this  :shrug:

Link to comment
Share on other sites

If what you are showing would be arrays in an array then you would use the multisort example but with key position.  But your second example is re-ordering not sorting so that would take looping through,comparing and re-ordering on the result of the comparison.

 

 

HTH

Teamatomic

Link to comment
Share on other sites

I'm with roopurt18 on this. Let's see how you are getting the data. However, if there is no way to sort the databefore putting it into an array, then usort() will be a better solution than array_multisort().

 

array_multisort() will require you to reformat the multidimensional array into many arrays before running it. With usort, you can create a small function to resort the multidimensional array however you want. If you were to provide the structure of your array I could provide some sample code. Use print_r() as already suggested above. Your examples do not show structure: are the values numerically indexed or what?

Link to comment
Share on other sites

I'm guessing his values are numerically indexed and that they are strings in the format he has provided.

 

I'm also guessing there is a way he can do this while retrieving the values or he can retrieve the values in a modified manner that will make this sorting task easier.  If he is unable to elaborate on his methods and formats, then there's only so much we can do to help.

Link to comment
Share on other sites

Sure, I was just trying to keep it simple....maybe achieving the opposite  :D

 

foreach($database_array as $x){
$db = "F:\location\\$x.mdb";
$conn = new COM('ADODB.Connection') or exit('Cannot start ADO.');
$conn->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=$db");

$sql = "SELECT * FROM MyTable ORDER By Status asc, ID desc";
$rs = $conn->Execute($sql);
while(!$rs->Eof){

	#bunch of results put into variables#

	$orders[] = ("$status||$id||$shop||$name||$orderdate");

	$rs->MoveNext();
}
$rs->Close();
}

 

Maybe it was misunderstood, each value of the array is just a string, not another array (put together to later be broken into one). So the examples I gave before were strings. The real values look that way. I was hoping there was some way to pick apart a string for sorting.

I don't understand usort very well....it seemed like that was the idea behind it.

Link to comment
Share on other sites

each value of the array is just a string

I managed to pick up on that.  :)

 

<?php
$sort_status = array(); // want to init these values
$sort_id = array(); // init
$orders = array(); // init

foreach($database_array as $x){
    $db = "F:\location\\$x.mdb";
    $conn = new COM('ADODB.Connection') or exit('Cannot start ADO.');
    $conn->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=$db");
    
    $sql = "SELECT * FROM MyTable ORDER By Status asc, ID desc";
    $rs = $conn->Execute($sql);
    while(!$rs->Eof){
        
        #bunch of results put into variables#
        $sort_status[] = $status; // the $sort_ARRAYS are for array_multisort
        $sort_id[] = $id;
        $orders[] = ( "$status||$id||$shop||$name||$orderdate" );
        
        $rs->MoveNext();
    }
    $rs->Close();
}

array_multisort( $sort_status, SORT_ASC, $sort_id, SORT_DESC, $orders );
print_r( $orders );
?>

 

put together to later be broken into one

If you're later going to be breaking the strings apart into arrays, then you may

want to assign to $orders like so:

$orders[] = array( 'status' => $status, 'id' => $id, ... );

 

(edit 1) Looping over all the records to build the array, then sorting the array, and then ultimately looping over it again is computationally expensive.  There might also be a way where you can create a joint dataset that allows you to select from all of the databases / tables at once and actually use the database to perform the sort.

 

(edit 2) However if the record set is small OR this script is not run often OR you just are not generally concerned with the performance, then array_multisort() is fine.

Link to comment
Share on other sites

This makes no sense to me:

$orders[] = ( "$status||$id||$shop||$name||$orderdate" );

 

I thought you were dealing with a multi-dimensional array. Instead you are taking the values and creating a sting with all the values concatenated. You should create a multidimensional array to keep the data organized and you can easily sort using usort(). usort() is a better option for sorting multidimensional arrays. array_multisort() would require you to create/maintaine separate arrays for each sort field (see Example #3 in the manual). With usort() you just need to create a small function to sort a multidimensional array.

 

Try this:

<?php

$orders = array(); // init

foreach($database_array as $x){
    $db = "F:\location\\$x.mdb";
    $conn = new COM('ADODB.Connection') or exit('Cannot start ADO.');
    $conn->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=$db");
    
    $sql = "SELECT * FROM MyTable ORDER By Status asc, ID desc";
    $rs = $conn->Execute($sql);
    while(!$rs->Eof){
        
        //Create a multi-dimensional array
        $orders[] = (
            'status' => $status,
            'id'        => $id,
            'shop'      => $shop,
            'name'      => $name,
            'orderdate' =>$orderdate
        );
    
        $rs->MoveNext();
    }
    $rs->Close();
}
    
//Create custom function for sorting array
function mySort($a, $b)
{
    //Sort by status, ascending
    if($a['status']!=$b['status'])
    {
        return ($a['status']<$b['status']) ? 1 : -1;
    }
    //Sort by ID descending
    return ($a['status']>$b['status']) ? 1 : -1;
}
//Sort array using usort() and the custom function
usort($orders, 'mySort');
print_r($orders);
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.