2012-10-13 142 views
1

我有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開發人員,不知道如何完成此任務。您的幫助將不勝感激。謝謝

回答

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

一個。您可以使用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) 
+0

現在內陣列是陣列 0 =>字符串 '7'(長度= 1) 1 =>串 '名字1'(長度= 6) 2 => string'8'(length = 1) 3 => string'4'(length = 1)我需要它作爲'id'=>'7', 'name'=>'Name 1', 'marks'=>'8', 'grade'=>'4'請幫忙 – Saleem

+0

@Saleem ok保持 – Baba

+1

+1 I lea甚至如果你還沒有(還有......)解決了$ key => $ value的問題;-)好的答案。 – Sepster