Reputation: 35
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
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);
array_values()
to reindexIf 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);
}
array_values()
to reindexUpvotes: 2