将多个关联数组合并到单个关联数组数组中

时间:2012-10-13 14:17:14

标签: php arrays multidimensional-array

我有4个关联数组,如下所示:

$ids  = array(
      '0' => '7' ,
      '1' => '8' ,
      '2' => '9'
);
$names = array (
      '0' => 'Name 1' ,
      '1' => 'Name 2' ,
      '2' => 'another name'
);
$marks = array(
      '0' => '8' ,
      '1' => '5' ,
      '2' => '8'
);
§grade = array(
      '0' => '4' ,
      '1' => '2.5' ,
      '2' => '4'
);

我想将它们“合并”到一个数组中,包含关联数组,如下所示:

$data = array(
   array(
      'id' => '7' ,
      'name' => 'Name 1' ,
      'marks' => '8',
      'grade' => '4'
   ),
   array(
      'id' => '8' ,
      'name' => 'Name 2' ,
      'marks' => '5',
      'grade' => '2.5'
   ),
   array(
      'id' => '9' ,
      'name' => 'another name',
      'marks' => '8',
      'grade' => '4'
   )
);

我是一名新的PHP开发人员,不知道如何实现这一目标。非常感谢您的帮助。谢谢

1 个答案:

答案 0 :(得分:6)

我相信这是你的数组

$ids = array('0' => '7','1' => '8','2' => '9');
$names = array('0' => 'Name 1','1' => 'Name 2','2' => 'another name');
$marks = array('0' => '8','1' => '5','2' => '8');
$grade = array('0' => '4','1' => '2.5','2' => '4');

#New Keys
$keys = array("id","name","marks","grade");

<强> A 即可。您可以使用MultipleIterator

$final = array();
$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($ids));
$mi->attachIterator(new ArrayIterator($names));
$mi->attachIterator(new ArrayIterator($marks));
$mi->attachIterator(new ArrayIterator($grade));

foreach ( $mi as $value ) {
    $final[] = array_combine($keys, $value);
}
var_dump($final);

<强>乙即可。您可以使用array_map

$final = array();
foreach ( array_map(null, $ids, $names, $marks, $grade) as $key => $value ) {
    $final[] = array_combine($keys, $value);
}
var_dump($final);

输出

array
  0 => 
    array
      'id' => string '7' (length=1)
      'name' => string 'Name 1' (length=6)
      'marks' => string '8' (length=1)
      'grade' => string '4' (length=1)
  1 => 
    array
      'id' => string '8' (length=1)
      'name' => string 'Name 2' (length=6)
      'marks' => string '5' (length=1)
      'grade' => string '2.5' (length=3)
  2 => 
    array
      'id' => string '9' (length=1)
      'name' => string 'another name' (length=12)
      'marks' => string '8' (length=1)
      'grade' => string '4' (length=1)