如何将变量添加到数组?

时间:2016-07-15 07:19:52

标签: php

我有这样的数组:

Array
(
    [0] => Array
        (
            [total] => 0
            [month] => May
        )

    [1] => Array
        (
            [total] => 1000000
            [month] => June
        )
)

我有这样的变量:$target = 3000000

我想将变量添加到数组

所以,结果如下:

Array
(
    [0] => Array
        (
            [total] => 0
            [month] => May
            [target] => 3000000
        )

    [1] => Array
        (
            [total] => 1000000
            [month] => June
            [target] => 3000000
        )
)

是否可以做到?

7 个答案:

答案 0 :(得分:1)

试试这种方式,

foreach($myArray as $key=>$value){
    $myArray[$key]['target'] = $target;
}
print_r($myArray); // To print array

答案 1 :(得分:0)

<?php 
  foreach($your_array as $k=>$v):
     $your_array[$k]['target'] = $target;
  endforeach;
?>

答案 2 :(得分:0)

如果您的目标是将target键添加到主阵列中的所有子阵列,就像您发布的那样,您可以使用这样的循环来实现:

    <?php
        $target    = 3000000;
        $mainArray = array(
           array(
             'total' => 0,
             'month' => 'May',
           ),
           array(
             'total' => 1000000,
             'month' => 'June',
           ),
        );

        foreach($mainArray as $key=>&$subArrays){
            $subArrays['target'] = $target;
        }

        var_dump($mainArray);  //<== SHOULD CONTAIN THE ENTRY: target.

        //DUMPS
        array(
           array(
             'total' => 0,
             'month' => 'May',
             'target' => 3000000,
           ),
           array(
             'total' => 1000000,
             'month' => 'June',
             'target' => 3000000,
           ),
        );

确认结果here

答案 3 :(得分:0)

使用array_merge

$target = ['target' => 3000000];

foreach ($array as &$item) {
     $item = array_merge($item, $target);
}

答案 4 :(得分:0)

如果你总是知道变量名,那么你可以这样做

$target = 3000000
foreach($array as $key => $val){
   $array[$key]['target'] = $target;//create new index "target" and assign the value
}

注意: $array是您当前的数组

输出

Array
(
[0] => Array
    (
        [total] => 0
        [month] => May
        [target] => 3000000
    )

[1] => Array
    (
        [total] => 1000000
        [month] => June
        [target] => 3000000
    )
)

答案 5 :(得分:0)

这是更简单的方法。不需要额外的数组初始化。

foreach($ array as $ key =&gt;&amp; $ value){     $ value ['target'] = 5000; }

的print_r($阵列);

答案 6 :(得分:0)

Php的array_map允许您将函数应用于数组的每个元素。

DROP TABLE #tmpResult;

输出:

<?php

$input = array
    (
        array
            (
                'total' => 0,
                'month' => 'May'
            ),
        array
            (
                'total' => 1000000,
                'month' => 'June'
            )
    );

$output = array_map
    (
        function($item) {
            $item['target'] = '3000000';
            return $item;
        },
        $input
    );

var_export($output);