2012-10-12 158 views
0

我在猜測我完全錯了,但我想將數組添加到foreach循環正在運行的數組的末尾。PHP foreach將數組添加到foreach循環運行的數組的末尾

E.g這是開始結果

array(3) { 
    [0]=> 
    array(1) { 
    ["name"]=> 
    string(7) "Matthew" 
    } 
    [1]=> 
    array(1) { 
    ["name"]=> 
    string(3) "Jim" 
    } 
    [2]=> 
    array(1) { 
    ["name"]=> 
    string(3) "Sam" 
    } 
} 

這是使用

<?php 

    $arr = array(array("name" => "Matthew"), array("name" => "Jim"), array("name" => "Sam")); 

    foreach ($arr as $element) { 

    $ages = array("test" => 12); 

    $element['test'] = $ages; 

} 

?> 

所需的最終結果的代碼IM

array(3) { 
    [0]=> 
    array(1) { 
    ["name"]=> 
    string(7) "Matthew", 
    array(1) { 
    ["test"]=> 
    int(2) 12 
    } 
    } 
    [1]=> 
    array(1) { 
    ["name"]=> 
    string(3) "Jim", 
    array(1) { 
    ["test"]=> 
    int(2) 12 
    } 
    } 
    [2]=> 
    array(1) { 
    ["name"]=> 
    string(3) "Sam", 
    array(1) { 
    ["test"]=> 
    int(2) 12 
    } 
    } 
} 

回答

0

嘗試此

foreach ($arr as $key=>$val) { 
    $ages = array("test" => 12); 
    $arr[$key]['test'] = $ages; 
} 

結果是

Array (
    [0] => Array 
     (
      [name] => Matthew 
      [test] => Array 
       (
        [test] => 12 
       ) 
     ) 
    [1] => Array 
     (
      [name] => Jim 
      [test] => Array 
       (
        [test] => 12 
       ) 
     ) 
    [2] => Array 
     (
      [name] => Sam 
      [test] => Array 
       (
        [test] => 12 
       ) 
     )) 
+0

乾杯人的作品魅力 –