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.

2
  • 1
    Are you sure you want the arrays numbered 1 and 2, not 0 and 1? Commented Nov 7, 2013 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. Commented Apr 23, 2022 at 1:46

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.