PHP - Sort multi-dimensional array by another array

前端 未结 5 1044
忘掉有多难
忘掉有多难 2020-12-06 17:59

I\'m trying to sort a multi-dimensional array by another array, but have so far come up short.
array_multisort seems be working only for real sorting.

Suppose I

5条回答
  •  情歌与酒
    2020-12-06 18:50

    For those of you who want to sort data based on an array with actual IDs, rather than based on an array with indexes like in the accepted answer - you can use the following simple comparison function for the usort:

    usort($data, function($a, $b) use ($order) {
        $posA = array_search($a['id'], $order);
        $posB = array_search($b['id'], $order);
        return $posA - $posB;
    });
    

    So the following example will work fine and you won't get the Undefined offset notices and an array with null values:

    $order = [20, 30, 10];
    
    $data = [
        ['id' => 10, 'title' => 'Title 1'],
        ['id' => 20, 'title' => 'Title 2'],
        ['id' => 30, 'title' => 'Title 3']
    ];
    
    usort($data, function($a, $b) use ($order) {
        $posA = array_search($a['id'], $order);
        $posB = array_search($b['id'], $order);
        return $posA - $posB;
    });
    
    echo '
    ', var_dump($data), '
    ';

    Output:

    array(3) {
      [0]=>
      array(2) {
        ["id"]=>
        int(20)
        ["title"]=>
        string(7) "Title 2"
      }
      [1]=>
      array(2) {
        ["id"]=>
        int(30)
        ["title"]=>
        string(7) "Title 3"
      }
      [2]=>
      array(2) {
        ["id"]=>
        int(10)
        ["title"]=>
        string(7) "Title 1"
      }
    }
    

提交回复
热议问题