I have a multi-dimensional PHP array and want to remove any elements (on a row basis) which do not match a value.
For example:
$user_types = [
0 => ['ut_id' => 32, 'type' => 'admin'],
1 => ['ut_id' => 31, 'type' => 'user'],
2 => ['ut_id' => 801, 'type' => 'editor']
];
Let's say I only want the element where 'type' == 'admin'
. I want the output to be:
$user_types = [
0 => ['ut_id' => 32, 'type' => 'admin']
]
I also need to ensure that the array is keyed sequentially. So if I only want type == 'editor'
the array key should still be 0 (not 2), e.g.
$user_types = [
0 => ['ut_id' => 801, 'type' => 'editor']
]
I've had a look at PHP array delete by value (not key) but this does not deal with multi-dimensional arrays.
I've also seen some solutions which use a foreach
loop, but that seems quite inefficient.
Please can someone point me in the direction of what to look at? I can't find any examples that deal with this when it comes to multidimensional arrays. I have seen Delete element from multidimensional-array based on value but this seems inefficient and was written about 6 years ago.