0

I'm working on some code for an online store to write orders to a txt file once they have been placed.

To generate this string I am using the following code... However it is only writing the information for the very last item in the array. I know that this is because as it runs through the foreach loop it is discarding previous information but have not been able to think of a way to counter this.

Any suggestions of a different way to tackle this?

foreach($_SESSION['itemname'] as $key=>$value) {
    $output_products =""
    ."item: ". $_SESSION['itemname'][$key] ."\t"
    ."qty: ".$_SESSION['itemqty'][$key]."\t"
    ."price: ".$_SESSION['itemprice'][$key]."\t"
    ."Sub Total: ".$_SESSION['subtotal'][$key]."\t";
}
$output_string = ""
.$_SESSION['fname'] ."\t"
.$_SESSION['lname'] ."\t"
.$_SESSION['address'] ."\t"
.$output_products ."\t"
.$_SESSION['grandTotal']."\n";
4

1 回答 1

2

change

foreach($_SESSION['itemname'] as $key=>$value) {
    $output_products =""
    ."item: ". $_SESSION['itemname'][$key] ."\t"
    ."qty: ".$_SESSION['itemqty'][$key]."\t"
    ."price: ".$_SESSION['itemprice'][$key]."\t"
    ."Sub Total: ".$_SESSION['subtotal'][$key]."\t";
}

to

$output_products ="";
foreach($_SESSION['itemname'] as $key=>$value) {
    $output_products .=""
    ."item: ". $_SESSION['itemname'][$key] ."\t"
    ."qty: ".$_SESSION['itemqty'][$key]."\t"
    ."price: ".$_SESSION['itemprice'][$key]."\t"
    ."Sub Total: ".$_SESSION['subtotal'][$key]."\t";
}

You can use .= for appending strings.

于 2013-05-27T04:32:15.733 回答