douyu1656 2016-11-14 10:06
浏览 41

通过引用重新设置多维数组中的数组键,递归

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)
  }
}
  • 写回答

2条回答 默认 最新

  • douxue4242 2016-11-14 10:22
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染