0

我猜我这样做完全错误,但我想在 foreach 循环正在运行的数组的末尾添加一个数组。

例如,这是开始的结果

 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;

}

?>

期望的最终结果

    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
  }
  }
}
4

1 回答 1

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
                )
        ) )
于 2012-10-12T13:40:44.797 回答