0

我有没有键的嵌套数组。我想按特定顺序添加键。什么是干净的方法来做到这一点?

从这个数组开始。它仅按位置索引。

[0] => (
    [0] => Tyler
    [1] => Durden
    [2] => 05/07/1985
)
[1] => (
    [0] => Edward
    [1] => Norton
    [2] => 03/21/1988
)

现在按顺序应用这些键:

['first_name'] =>
['last_name'] =>
['birthday'] =>

最终数组:

[0] => (
   ['first_name'] => Tyler
   ['last_name'] => Durden
   ['birthday'] => 05/071985
)
[1] => (
    ['first_name'] => Edward
    ['last_name'] => Norton
    ['birthday'] => 03/21/1988
)

如果您的代码允许任何关键结构,而不是硬编码,则可以加分!

4

2 回答 2

4

我认为array_combine可以解决问题:

foreach ($bigarray as &$x) {
  $x = array_combine(array('first_name','last_name','birthday'),$x);
}
于 2012-08-15T18:39:02.070 回答
0

还有经典的算法:

foreach ( $array as $key=>$value ) {
   $array[$key]['first_name'] = $array[$key][0];
   $array[$key]['last_name'] = $array[$key][1];
   $array[$key]['birthday'] = $array[$key][2];
   unset($array[$key][0]);
   unset($array[$key][1]);
   unset($array[$key][2]);
}
于 2012-08-15T18:45:07.027 回答