N
N
nvjfdvjnkn2018-03-07 15:46:49
PHP
nvjfdvjnkn, 2018-03-07 15:46:49

How to filter multidimensional array?

$array1 = array(
  array(
    "id" => 123,
    "title" => "aaa"),
  array(
    "id" => 456,
    "title" => "bbb"),
  array(
    "id" => 789,
    "title" => "ccc"),
  array(
    "id" => 101,
    "title" => "ddd")
);

$array2 = array(123, 789);

The array2 array consists of the id of the products to be obtained from the array1
As a result, you need to either get a new array or remove the excess from array1
UPDATE:
The array2 array looks like this:
$array2 = array(
  array(
    3 => 123),
  array(
    4 => 456)
);

Answer the question

In order to leave comments, you need to log in

3 answer(s)
0
0xD34F, 2018-03-07
@nvjfdvjnkn

$ids = array_map(function($n) {
  return array_values($n)[0];
}, $array2);

$array1 = array_filter($array1, function($n) use($ids) {
  return in_array($n['id'], $ids);
});

R
RidgeA, 2018-03-07
@RidgeA

The task is trivial and there are many ways to solve it.
What exactly does not work in your solution?

S
Stanislav B, 2018-03-07
@S_Borchev

you can use array_filter

$result = array_filter($array1, function ($item) use ($array2) {
   return in_array($item['id'], $array2);
});

well, either in the loop check each element from the first array

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question