2

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.

Nicholas Summers
  • 4,444
  • 4
  • 19
  • 35
  • Do these arrays come out of nowhere, or perhaps from a database query? (which could be easier changed to return only associative arrays) – mario Oct 26 '14 at 04:43
  • They come from a database query, however it would be good to know how to do this on arrays where the exact keys aren't know. (there are a few APIs that return these kinds of arrays too.) – Nicholas Summers Oct 26 '14 at 04:45
  • 1
    See array_intersect/filter answer in duplicate; though might need a second callback for nested lists, and would still be slower than just using *FETCH_ASSOC. – mario Oct 26 '14 at 04:48
  • @mario I can't get any of those methods working for this array (only effecting top level array) – Nicholas Summers Oct 26 '14 at 04:51

1 Answers1

2

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.

Demo

Amal Murali
  • 75,622
  • 18
  • 128
  • 150