1

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)
  }
}
1
  • 1
    Can you post some input along with expected output Commented Nov 14, 2016 at 10:13

2 Answers 2

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.

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

Comments

0

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);
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.