PHP将特定键值添加到预先存在的数组中

时间:2013-06-30 17:10:37

标签: php arrays insert

我有一个数组:

$test = Array
        (
            ["foo"] => Array
                (
                    ["totalsales"] => 80
                    ["totalamount"] => 4
                )
         (

我想添加带有值的新索引:

$test["foo"][$date] = 20; // $date = 2013-06-30
$test["foo"][$date] = 40; // $date = 2013-06-25

输出如下:

$test = Array
        (
            ["foo"] => Array
                (
                    ["totalsales"] => 80
                    ["totalamount"] => 4
                    ["2013-06-25"] => 40
                )
         (

我希望数组看起来像这样:

$test = Array
        (
            ["foo"] => Array
                (
                    ["totalsales"] => 80
                    ["totalamount"] => 4
                    ["2013-06-30"] => 20
                    ["2013-06-25"] => 40
                )
         (

如何做到这一点?谢谢你,我的英语不好。

1 个答案:

答案 0 :(得分:1)

您提供的代码无法解析。

确保$date变量包含它应该包含的内容,因为(除语法问题外)您的示例完全可以正常运行:

<?php
$test = array
(
    'foo' => array
    (
        'totalsales' => 80,
        'totalamount' => 4
    )
);

$date = '2013-06-30';
$test['foo'][$date] = 20;

$date = '2013-06-25';
$test['foo'][$date] = 40;

print_r($test);

输出:

Array
(
    [foo] => Array
        (
            [totalsales] => 80
            [totalamount] => 4
            [2013-06-30] => 20
            [2013-06-25] => 40
        )
)