0

How do I run a array_map on a triple dimensional array? Where I want to "clear" the innermost array?

It looks like this:

Array
(
    [1] => Array
        (
            [1] => Array
                (
                    [cat] => Hello!
                    [url] => hello
                )

            [5] => Array
                (
                    [cat] => Good job!
                    [url] => good-job
                )

    [2] => Array
        (
            [2] => Array
                (
                    [cat] => How are you?
                    [url] => how-are-you
                )

            [6] => Array
                (
                    [cat] => Running shoes
                    [url] => running-shoes
                )
        )
)

I want to make it look like this:

Array
(
    [1] => Array
        (
            [1] => Array
                (
                    [cat] => Hello!
                    [url] => hello
                )

            [2] => Array
                (
                    [cat] => Good job!
                    [url] => good-job
                )

    [2] => Array
        (
            [1] => Array
                (
                    [cat] => How are you?
                    [url] => how-are-you
                )

            [2] => Array
                (
                    [cat] => Running shoes
                    [url] => running-shoes
                )
        )

)

This solution Reset keys of array elements in php? "just" works on tow diemensional arrays, if Im not wrong.

Community
  • 1
  • 1
JohnSmith
  • 417
  • 4
  • 10
  • 21
  • 1
    Are you sure you want the arrays numbered `1` and `2`, not `0` and `1`? – gen_Eric Nov 07 '13 at 16:12
  • You call just implement the re-keying within a loop. @JohnSmith Use as many loops as you need to to access the appropriate level. We don't necessarily need a new question on SO for every array depth where `array_values()` should be called. – mickmackusa Apr 23 '22 at 01:46

1 Answers1

0

you could write a short function to do it with array_map:

function mappingfunction($array){
    $remappedarray = array();
    foreach($array as $layer){
        $remappedarray[] = array_map('array_values', $array);
    }

    return $remappedarray;
}

if you want to preserve the keys:

function mappingfunction($array){
        $remappedarray = array();
        foreach($array as $key => $layer){
            $remappedarray[$key] = array_map('array_values', $array);
        }

        return $remappedarray;
    }

Untested, but should point you in the right direction.

tobynew
  • 337
  • 1
  • 3
  • 17