0

Here is my array:

$arr = [
        1 => [
              2 => "something",
              3 => "something else"
            ],
        2 => "foo br"
    ];

I need to restart all keys and start all of them from 0. Based on some researches, I figured out I have to use array_values() function. But it just makes the keys of outer array re-index, See.

How can I apply it on the all keys of array? (even nested ones)

1
  • 1
    loop through the parent array and use array_values on each child array Commented Jan 15, 2017 at 9:17

3 Answers 3

4

You can use array_values + recursively calling custom function:

function arrayValuesRecursive($array) {
    $array = array_values($array);
    $countValues = count($array);
    for ($i = 0; $i < $countValues; $i++ ) {
        $subElement = $array[$i];
        if (is_array($subElement)) {
            $array[$i] = arrayValuesRecursive($subElement);
        }
    }
    return $array;
}

$restructuredArray = arrayValuesRecursive($array);
Sign up to request clarification or add additional context in comments.

2 Comments

Yes this would work for the example in the question. But what about arrays contain 5 nested arrays?
@stack It should also works because it does not depends on exact nested deep, it will loop recursively through each level
2

You can implement it using recursion like this:

function reIndex($arr) {
    $arr = array_values($arr);
    foreach ($arr as $k => $v) {
        if (is_array($v)) {
            $arr[$k] = reIndex($v);
        }
    }

    return $arr; 
}

$arr = reIndex($arr);

2 Comments

Yes this would work for the example in the question. But what about arrays contain 5 nested arrays?
@stack It would also work. As far as I see this does the same as sergio's code, but it's shorter
1

Hi checkout following code

<?php
    $arr = [
        1 => [
            2 => "something",
            3 => "something else"
        ],
        2 => "foo br"
    ];

    $reIndexedArray = array();
    foreach($arr as $arrItr){
        $reIndexedArray[] = count($arrItr) > 1 ? array_values($arrItr) : $arrItr;
    }
    print_r($reIndexedArray);
?>

output is

Array
(
    [0] => Array
        (
            [0] => something
            [1] => something else
        )

    [1] => foo br
)

2 Comments

count($arrItr) > 1? And if $arrItr is an array with 1 item?
Yes this would work for the example in the question. But what about arrays contain 5 nested arrays?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.