Skip to content
Advertisement

Preserve elements in each row of a two-dimensional array based on another array

I have this array:

JavaScript

What I am looking for is a way to get a multiple array with only required columns (array_column is not a option, since it’s give me only 1 column).

What I have done

JavaScript

The problem is that it seems too laggy, since it iterates twice over this. Is there any way to get multiple columns without this workaround?

I’m using PHP5.6

Advertisement

Answer

I think the bigger issue is you lose the keys

Original Code

JavaScript

You can use a simple foreach instead of the second array_map:

JavaScript

Output

JavaScript

Sandbox

the problem is that it seems too laggy, since it iterates twice over this.

There is no real way to not iterate over it 2 times, but you probably don’t want to throw away the keys either.

That said you can recursively unset the items you don’t want.

JavaScript

Same output as before

This is easier to do by reference. Rather or not that is faster you’ll have to test the 2 and see.

Sandbox

As a final note you shouldn’t assume the key will exist or that keys will be an array unless you type cast it as an array.

You could also do it with array filter

JavaScript

There is some small performance benefit to declaring the function for filtering outside of the loop (array_map).

Sandbox

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement