2013-06-30 66 views
0

我有一個數組:PHP添加特定鍵值到預先存在的陣列

$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 
       ) 
     (

這怎麼辦?謝謝你爲我的英語不好。

+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 
     ) 
) 
+0

感謝您的快速回復。我在我的代碼的以前部分有一個錯誤:-) – exar