开发者

Sort multidimensional array by unidimensindal array

The multidim. array looks like:

$arr = array(
  array(
    'id' => 'first',
    'name' => 'John',
    'age' => 17,
  ),

  array(
    'id' => 'second',
    'name' =&开发者_如何学运维gt; 'Mary',
    'age' => 26,
  ),

  array(
    'id' => 'third',
    'name' => 'Eve',
    'age' => 21,
  ),

);

And the array which decides how $arr is sorted looks like:

$sort_by = array('third', 'first', 'second');

So what I want is to sort the elements of the first array based on its id field and the second array.

In this case the 1st array should be:

$arr = array(
  array(
    'id' => 'third',
    'name' => 'Eve',
    'age' => 21,
  ),

  array(
    'id' => 'first',
    'name' => 'John',
    'age' => 17,
  ),

  array(
    'id' => 'second',
    'name' => 'Mary',
    'age' => 26,
  ),


); 


function sort_by_1d($item_1, $item_2)
{
    $sort_by = array('third', 'first', 'second');
    $item_1_i = array_search($item_1['id'], $sort_by);
    $item_2_i = array_search($item_2['id'], $sort_by);
    return $item_1_i - $item_2_i;
}

usort($arr, 'sort_by_1d');


$sortedArray = array();
foreach($sort_by as $sort){
  foreach($arr as $val){
    if($val['id'] === $sort){
      $sortedArray[] = $val;
    }
  }
}

Stolen from: Sort Array Subkey Based on Another Array's Order

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜