Reputation: 4756
So I have a PHP array like so:
Array
(
[0] => Array
(
[offset] => 1
[0] => 1
[name] => Value:990937970
[1] => Value:990937970
)
[1] => Array
(
[offset] => 2
[0] => 2
[name] => Value:482758260
[1] => Value:482758260
)
[2] => Array
(
[offset] => 3
[0] => 3
[name] => Value:2045053536
[1] => Value:2045053536
)
)
But I want to change it so that the numeric keys are not returned, like this:
Array
(
[0] => Array
(
[offset] => 1
[name] => Value:990937970
)
[1] => Array
(
[offset] => 2
[name] => Value:482758260
)
[2] => Array
(
[offset] => 3
[name] => Value:2045053536
)
)
My Question: Is there a simple way (without a foreach
or while
loop) to strip out these numeric keys?
I know that I can just do a foreach
where I check if $key is a string; however, loops add to my code's cyclomatic complexity so I am trying to avoid them.
Upvotes: 2
Views: 2439
Reputation: 1630
It's an old question, but this may be what you are looking for. You filter over the array given the key and remove any which value which key is numeric:
array_filter($input, fn($key) => !is_numeric($key), ARRAY_FILTER_USE_KEY);
Upvotes: 0
Reputation: 76636
Well, if you really don't want to use a foreach
, you can do:
array_walk($data, function (&$v) {
$keys = array_filter(array_keys($v), function($k) {return !is_int($k);});
$v = array_intersect_key($v, array_flip($keys));
});
array_walk()
still does the looping just as a foreach
would; it just isn't explicitly shown.
Also, as mario said, modifying the database query would be a much recommended course of action than this. If you must do this on the PHP side, a foreach would be lot more efficient.
Upvotes: 2