开发者

Sort multidimensional array by unidimensindal array

开发者 https://www.devze.com 2023-03-26 13:10 出处:网络
The multidim. array looks like: $arr = array( array( \'id\' => \'first\', \'name\' => \'John\', \'age\' => 17,

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

精彩评论

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