PHP使用具体值对多个数组进行排序

时间:2018-08-19 12:33:48

标签: php arrays sorting

我有如下数组:

$arr = [
        0=>['note_id'=>1,'content'=>1],
        1=>['note_id'=>2,'content'=>2],
        2=>['note_id'=>3,'content'=>3],
    ];

我有一组ID:

$ids=[2,3,1];

我需要通过使用值'note_id'和数组 id 对数组进行排序来从 arr 获取新数组,因此resut必须为:

   $arr = [
            1=>['note_id'=>2,'content'=>2],
            2=>['note_id'=>3,'content'=>3],
            0=>['note_id'=>1,'content'=>1],
        ];

有任何功能吗?谢谢!

1 个答案:

答案 0 :(得分:0)

您可以循环这两个数组,并将$arr的键与$ids的值进行比较,然后创建新数组$newArr

$arr = [
    0 => ['note_id' => 1, 'content' => 1],
    1 => ['note_id' => 2, 'content' => 2],
    2 => ['note_id' => 3, 'content' => 3],
];
$ids = [2, 3, 1];
$newArr = [];
foreach ($ids as  $id) {
    foreach ($arr as $keyArr => $item) {
        if ($id === $item['note_id']) {
            $newArr[$keyArr] = $item;
        }
    }
}
print_r($newArr);

结果:

Array
(
    [1] => Array
        (
            [note_id] => 2
            [content] => 2
        )

    [2] => Array
        (
            [note_id] => 3
            [content] => 3
        )

    [0] => Array
        (
            [note_id] => 1
            [content] => 1
        )

)

Demo