0

How can I succeed to filter a multidimensional with a help of other array value as keys for the first array.

$multidimensional = [
    ['var1' => 'val1'],
    ['var2' => 'val2'],
    ['var3' => 'val3'],
    ['val4' => 'val4'],
];
$filter = [1, 3];

The final result should be:

$multidimensional = [
    1 => ['var2' => 'val2'],
    3 => ['val4' => 'val4']
];

It should be something similar to array_slice() or some other method. How can I easily perform such a task?

1

3 Answers 3

2

You can use the array_intersect_key function:

$result = array_intersect_key($multidimensional, array_flip($filter));
Sign up to request clarification or add additional context in comments.

Comments

1

To expand upon my comment with a small example

<?php

$arrayOne = [
    1 => ['foo' => 'bar'],
    2 => ['foo' => 'bar'],
    3 => ['foo' => 'bar'],
    4 => ['foo' => 'bar'],
];

$arrayTwo = [1 => [], 3 => []];

print_r(array_intersect_key($arrayOne, $arrayTwo));

see array_intersect_key on php.net

Comments

1

Another variation using array_diff_key and array_flip functions:

$multidimensional = array_diff_key($multidimensional, array_diff_key($multidimensional, array_flip($filter)));

print_r($multidimensional);

The output:

Array
(
    [1] => Array
        (
            [var2] => val2
        )

    [3] => Array
        (
            [val4] => val4
        )
)

http://php.net/manual/en/function.array-diff-key.php

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.