I want to reset keys in a big, multidimensional array. I already found a solution which is actually work:
$fix_keys = function(array $array) use (&$fix_keys)
{
foreach($array as $k => $val)
{
if (is_array($val))
{
$array[$k] = $fix_keys($val);
}
}
return array_values($array);
};
and the problem is, if I pass big arrays to it, it becomes slow and memory consuming. What about refactoring with working references:
$fix_keys = function(array &$array) use (&$fix_keys)
{
foreach($array as $k => &$val)
{
if (is_array($val))
{
$array[$k] = $fix_keys($val);
}
}
unset($val);
$array = array_values($array);
};
but it messed up the array, all I get is [0] => null
. What is wrong?
Edit: so input data:
$a = [
'a' => 1,
'b' => 2,
'c' => [
'aa' => 11,
'bb' => [
'ccc' => 1
],
'cc' => 33
]
];
and I want to have:
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
array(3) {
[0]=>
int(11)
[1]=>
array(1) {
[0]=>
int(1)
}
[2]=>
int(33)
}
}
John SmithJohn Smith
asked Nov 14, 2016 at 10:06
-
1Can you post some input along with expected outputNarendrasingh Sisodia– Narendrasingh Sisodia2016年11月14日 10:13:40 +00:00Commented Nov 14, 2016 at 10:13
2 Answers 2
If memory is an issue you can try using yield
. I'm not sure if this fits your needs, but here it is:
function reduce($array){
foreach($array as $key => $value){
if(is_array($value)){
reduce($value);
}
}
yield array_values($array);
}
You can also use send
if you need to apply some logic to the generator.
answered Nov 14, 2016 at 10:22
Comments
I found the solution:
$fix_keys = function(array &$array) use (&$fix_keys)
{
foreach(array_keys($array) as $k)
{
if (is_array($array[$k]))
{
$fix_keys($array[$k]);
}
}
$array = array_values($array);
};
answered Nov 14, 2016 at 10:57
Comments
lang-php