Jump to content

Sorting an array with a delimiter


DaltonRandall

Recommended Posts

Hi there,

 

Let's say I have the following array:

Array
(
    [1] => 4224:3
    [2] => 4407:6
    [3] => 4403:5
    [4] => 4190:4
    [5] => 4194:2
    [6] => 4185:1
)

I want to sort it based on what follows the colon ( : ) in each value.  For example, I would like the result to be:

Array
(
    [6] => 4185:1
    [5] => 4194:2
    [1] => 4224:3
    [4] => 4190:4
    [3] => 4403:5
    [2] => 4407:6
)

I have found some code to allow me to sort the array as such, but it is resetting all of the keys (which are very important).  Does anyone have an efficient way to help me sort the array while keeping the key and value relationship intact?

 

Thanks a bunch in advance for any help! :)

Link to comment
Share on other sites


function cmp($a, $b)
{
$pieces_a = explode(":", $a);
$pieces_b = explode(":", $b);

if(!isset($pieces_a[1]) && isset($pieces_b[1])) {
return 1;
}
elseif(!isset($pieces_b[1]) && isset($pieces_a[1])) {
return -1;
}
elseif(!isset($pieces_a[1]) && !isset($pieces_b[1])) {
return 0;
}

if(substr($pieces_a[1], 0, 1) == '0') {
return 1;
}
elseif(substr($pieces_b[1], 0, 1) == '0') {
return -1;
}

$a = substr($pieces_a[1], 0, 1);
$b = substr($pieces_b[1], 0, 1);

return strcasecmp($a, $b);
}

 

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.