tags:

views:

70

answers:

3

I have an array of 15000 elements each of which is an array of 4 elements. I want to sort by the second element of the 4. Originally I made the original array's keys the second element and then k-sorted but unfortunately, some of the second elements are duplicates and since one key can't refer to multiple elements i lost some elements in transition. I could bubble sort by the second element but I'm looking for something that runs at least on the order of nlog(n). Can anyone think of a good algorithm (or possibly a function in php that I don't know about) that can sort by the second element? Thank you!

+3  A: 

I think you can use usort and define the cmp_function to use the second element.

Soufiane Hassou
A: 

I don't know what the internal implementation of usort is, but I'd bet it's better than bubblesort (it's probably quicksort).

timdev
+1  A: 

As others have stated, usort or uasort to maintain the array keys is what you want:

<?php

$myArray = array(
    'fruits' => array(
        array('apples', 'oranges', 'bananas')              
    ),
    'vegetables' => array(
        array('lettuce', 'carrots', 'peas')
    ),
    'monkeys' => array(
        array('Curious George', 'Amy', 'Marcel')
    )
);

// PHP 5.3+ example using a closure

uasort($myArray, function(array $a, array $b) {
    // Use whatever sorting algorithm you like
    return strnatcasecmp($a[1], $b[1]); 
});

var_export($myArray);

Running the above will output:

array (
  'monkeys' => 
  array (
    0 => 
    array (
      0 => 'Curious George',
      1 => 'Amy',
      2 => 'Marcel',
    ),
  ),
  'vegetables' => 
  array (
    0 => 
    array (
      0 => 'lettuce',
      1 => 'carrots',
      2 => 'peas',
    ),
  ),
  'fruits' => 
  array (
    0 => 
    array (
      0 => 'apples',
      1 => 'oranges',
      2 => 'bananas',
    ),
  ),
)

Here's an example that doesn't use a closure for pre PHP 5.3:

sortFunc(array $a, array $b)
{
    return strnatcasecmp($a[1], $b[1]); 
}

uasort($myArray, 'sortFunc');
Michael
i think you should point out that closures and thus your solution are supported only in php 5.3.0 and greater
Scott Evernden
This example uses a closure and only works with PHP 5.3+ :)
Michael