[ create a new paste ] login | about

Link: http://codepad.org/Q7EcTSfs    [ raw code | output | fork ]

PHP, pasted on Oct 19:
<?php

$order = array(2,3,1);
$order = array_flip($order);

$data = array(
    array('id' => 1, 'title' => 'whatever'),
    array('id' => 2, 'title' => 'whatever'),
    array('id' => 3, 'title' => 'whatever')
);

function cmp($a, $b)
{
    global $order;

    $posA = $order[$a['id']];
    $posB = $order[$b['id']];

    if ($posA == $posB) {
        return 0;
    }
    return ($posA < $posB) ? -1 : 1;
}

usort($data, 'cmp');

var_dump($data);


Output:
array(3) {
  [0]=>
  array(2) {
    ["id"]=>
    int(2)
    ["title"]=>
    string(8) "whatever"
  }
  [1]=>
  array(2) {
    ["id"]=>
    int(3)
    ["title"]=>
    string(8) "whatever"
  }
  [2]=>
  array(2) {
    ["id"]=>
    int(1)
    ["title"]=>
    string(8) "whatever"
  }
}


Create a new paste based on this one


Comments: