我需要用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);
}
答案 0 :(得分:1)
这一行:
$txarray = array('CartID' => $CartVar, 'Date' => $CartDate, 'Amount' => $CartTotal);
销毁你在之前的迭代中创建的任何先前数组。
答案 1 :(得分:1)
查看上面的代码片段$ txarray变量因代码而被覆盖。
$txarray = array('CartID' => $CartVar, 'Date' => $CartDate, 'Amount' => $CartTotal);
需要用
替换它$txarray[] = array('CartID' => $CartVar, 'Date' => $CartDate, 'Amount' => $CartTotal);
或者你也可以使用array_push()函数来推送数组,从而产生多维数组。 e.g。
array_push($txarray,array('CartID' => $CartVar, 'Date' => $CartDate, 'Amount' => $CartTotal));
有关array_push函数的更多文档,请参阅下面提到的url中的文档。 http://php.net/manual/en/function.array-push.php