Firefox add-ons Resizing / converting images in php

PHP usort: sort an array of records using a particular sequence

sorting, array_search, array, usort, sort, tip, php

With PHP's usort function you are sorting an array using a custom function you have made:

function sort_by_title($a,$b)
{

  return strcasecmp($a['title'], $b['title']);

}
$myArray[0]['id'] = 1;
$myArray[0]['title'] = 'Hello';
$myArray[1]['id'] = 5;
$myArray[1]['title'] = 'Foo';
$myArray[2]['id'] = 6;
$myArray[2]['title'] = 'Foo etc';
.... and so on

usort($myArray, 'sort_by_title');

How about sorting the same array using a particular sequence of either ids, titles or whatever field of the record (using an array)?

Here is the solution:

(this example sorts the above array by a sequence that refers to the title field)

function sort_by_seq($a,$b)
{

  $seq = array('Foo', 'Hello', 'Foo etc');
  return array_search($a['title'], $seq) - array_search($b['title'], $seq);

}
usort($myArray, 'sort_by_seq');


Check out also another (sql related) tip for sorting sql result rows:

http://programming.pblogs.gr/general-tips.html which will be updated continuity with new tips.

στο άρθρο "PHP usort: sort an array of records using a particular sequence"

Το σχόλιο σας

Send as anonymous

No HTML tags allowed for this blog comments