0

我使用以下代码来填充子数组中的所有空键``

$array = array(
        'note' => array('test', 'test1'),
        'year' => array('2011','2010', '2012'),
        'type' => array('conference', 'journal', 'conference'),
    );

foreach ($array['type'] as $k => $v) {
  foreach($array as $element => $a) {
    $iterator = $array[$element];
    if(!isset($iterator[$k])){       
       $iterator[$key] = '';
    }
  }
}

print_r($array);

问题是它实际上并没有改变$array临时变量中的元素$iterator

我知道这是一个简单的问题,但我想找出最好和最快的解决方案。

4

2 回答 2

2

Looks like you have some typos. $key in the middle of the loops is never defined. $a should be the same value as $iterator[$k], so no need to set it.

Try this.

$array = array(
        'note' => array('test', 'test1'),
        'year' => array('2011','2010', '2012'),
        'type' => array('conference', 'journal', 'conference'),
    );

foreach ($array as $k => $v) {
  foreach($k as $element => $a) {
    if(!isset($a)){       
       $array[$element] = '';
    }
  }
}
于 2012-06-19T22:42:49.173 回答
2

你不需要 $iterator 变量,你可以这样做:

foreach ($array['type'] as $k => $v) {
  foreach($array as $element => $a) {
    if(!isset($array[$element][$k])){       
       $array[$element][$key] = '';
    }
  }
}

我还建议切换内部和外部循环,这样它更具可读性和效率。

foreach($array as $element => $a) {
       foreach ($array['type'] as $k => $v) {
        if(!isset($array[$element][$k])){       
           $array[$element][$key] = '';
        }
      }
    }
于 2012-06-19T22:46:59.707 回答