0

我需要用 sql 和循环创建一个多维数组。但是只有一个结果被设置到数组中,最后一个结果是覆盖以前的结果。数组结构如下所示:

 ->value = Array (4)
   CartID => "1299"
   Date => "2012-09-27 09:17:20"
   Amount => "85.00"
         0 => Array (8)
         CartStatus => "Purchased"
         Date => "2012-09-27 09:17:20"
         CartID => "1299"
         Sequence => "1"
         Amount => "-85.00"
         Comments => " , Refund Status: "

这是我的代码:

    $txarray = array();
    foreach ($data as $transaction) {
    $CartVar = $transaction['CartID'];
    $CartStatus = $transaction['Status'];
    $CartDate = $transaction['DateTime'];
    $CartTotal = $transaction['Total'];
    $txarray = array('CartID' => $CartVar, 'Date' => $CartDate, 'Amount' => $CartTotal);
        $sql1 = $db->query("SQL stuff");
        foreach ($sql1 as $refund) {
        $CartID = $refund['CartID'];
        $Sequence = $refund['Sequence'];
        $TrxType = $refund['TrxType'];
        $ParentID = $refund['ParentID'];
        $TotalSum = '-'.$refund['Amount'];
        $Comments = ' '.$refund['Comments'];
        $Comments .= ', Refund Status: '.ucwords($refund['Status']);
        $txarray[] = array('CartStatus' => $CartStatus, 'Date' => $CartDate, 'CartID' => $CartID, 'Sequence' => $Sequence, 'TrxType' => $TrxType, 'ParentID' => $ParentID, 'Amount' => $TotalSum, 'Comments' => $Comments);
    }
4

2 回答 2

1

这一行:

$txarray = array('CartID' => $CartVar, 'Date' => $CartDate, 'Amount' => $CartTotal);

破坏您在早期迭代中创建的任何先前数组。

于 2012-10-24T17:24:08.820 回答
1

查看上面的代码片段 $txarray 变量由于代码而被覆盖。

$txarray = array('CartID' => $CartVar, 'Date' => $CartDate, 'Amount' => $CartTotal);

它需要替换为

$txarray[] = array('CartID' => $CartVar, 'Date' => $CartDate, 'Amount' => $CartTotal);

或者,您可以使用 array_push() 函数来推送数组,从而生成多维数组。例如

 array_push($txarray,array('CartID' => $CartVar, 'Date' => $CartDate, 'Amount' =>      $CartTotal));

有关 array_push 函数的更多文档,请参阅下面提到的 url 中的文档。 http://php.net/manual/en/function.array-push.php

于 2012-10-24T17:37:02.833 回答