1

let's suppos we have the following two arrays

Let's suppose this is called $array1

Array
(
    [0] => Array
        (
            [Name] => Jack
            [Height] => 190
            [Shoe Size] => 40
        )

    [1] => Array
        (
            [Name] => Rose
            [Height] => 160
            [Shoe Size] => 52
        )

)

Suppose this is called $array2

Array
(
    [0] => Name
    [1] => Shoe Size
)

Now, what I need to do, is to keep the keys in $array1 which are found in $array2 as values, so the output I'm expecting is something like this

Array
(
    [0] => Array
        (
            [Name] => Jack
            [Shoe Size] => 40
        )

    [1] => Array
        (
            [Name] => Rose
            [Shoe Size] => 52
        )

)

I tried array_intersect and array_intersect_key but they're both failing. does anyone have any idea how to do this?

1
  • 2
    may not be most efficient, but a simple foreach loop would be easy Commented Apr 6, 2014 at 23:29

1 Answer 1

2

What you need is array_intersect_key with array_flip

$array3 = array_flip($array2);
foreach($array1 as &$a) {
   $a = array_intersect_key($a, $array3);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Not quite working, but I get your concept and might be able to work with it.
@ChosenWann Works exactly as expected. $array1 gets modified directly, if you want the output to be stored in a brand new array, replace $a = with $newarray[] = .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.