Heilan Cardoso
Heilan Cardoso

Reputation: 35

Multidimensional array_values only on integer keys

I'm trying to make code to organize an array. I have this code:

$arr =  array(0=>array('key 1'=>'value 1', 'key 2'=>'value 2', 'key 3'=> array('2'=>'more values 1', '5'=>'more values 2', 7=>'more values 3')),
              2=>array(0=>'value 1', 2=>'value 2', 4=> array('key 2'=>'more values 1', 'key 5'=>'more values 2', 'key 7'=>'more values 3')));

echo print_r($arr);

Yields:

Array
(
    [0] => Array
        (
            [key 1] => value 1
            [key 2] => value 2
            [key 3] => Array
                (
                    [2] => more values 1
                    [5] => more values 2
                    [7] => more values 3
                )
        )

    [2] => Array
        (
            [0] => value 1
            [2] => value 2
            [4] => Array
                (
                    [key 2] => more values 1
                    [key 5] => more values 2
                    [key 7] => more values 3
                )
        )
)

I wanted the keys to integers could be renamed with array_values(). The array needs output like this:

Array
(
    [0] => Array
        (
            [key 1] => value 1
            [key 2] => value 2
            [key 3] => Array
                (
                    [0] => more values 1
                    [1] => more values 2
                    [2] => more values 3
                )
        )

    [1] => Array
        (
            [0] => value 1
            [1] => value 2
            [2] => Array
                (
                    [key 2] => more values 1
                    [key 5] => more values 2
                    [key 7] => more values 3
                )
        )
)

But unfortunately I could not make a code that work.

Upvotes: 2

Views: 1332

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78994

It would be very rare that you would need to do this as you can access the array elements without incrementing keys, say with foreach(). But here is a recursive function:

function array_reindex_recursive(&$array) {
    if(is_int(key($array))) {
        $array = array_values($array);
    }
    foreach($array as $key => &$val) {
        if(is_array($val)) {
            array_reindex_recursive($val);
        }
    }
}    

array_reindex_recursive($arr);
  • Check the first key in the array to see if it is integer (this could be a problem if other keys are not integer)
  • If so run array_values() to reindex
  • Loop through the values and if one is an array call the function recursively

If you want to make sure that ALL keys are integer then replace the first if with something like this:

if(count(array_filter(array_keys($array), 'is_int')) == count($array)) {
    $array = array_values($array);
}
  • Filter out all non-integer keys and compare with the length of the original array
  • If the same length then all keys were integer, run array_values() to reindex

Upvotes: 2

Related Questions