1

I have array such as:

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

And I have array of ids:

$ids=[2,3,1];

I need get new array from arr by using the sorting this array by value 'note_id' and array ids, so resut must be:

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

Are there any functions for this? Thanks!

  • Possible duplicate of [How can I sort arrays and data in PHP?](https://stackoverflow.com/questions/17364127/how-can-i-sort-arrays-and-data-in-php) – user3942918 Aug 20 '18 at 05:52

1 Answers1

0

You could loop both the arrays and compare the keys of $arr with with the values of $ids and create your new array $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);

Result:

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

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

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

)

Demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70