简体   繁体   中英

How to output for each loop values in array values

I have got the following for each loop

 foreach ($jcart->get_contents() as $item) {  
  $reg1['items'][] = array(
    'description' => urlencode($item['name']),
    'amount' => urlencode($item['price']),
    'quantity' => urlencode($item['qty'])
  );
}  

Which out puts fine:

"items":[{"description":"Product1","amount":"519","quantity":"1"},{"description":"Product2","amount":"339","quantity":"1"}]}

However when I do the following it only gets the last item

$req = array( 
    array(
'action' => 'SALE',
'type' => 1,
'countryCode' => 826,
'currencyCode' => 826),
 
    'items' => array(
    'description' => urlencode($item['name']),
    'amount' => urlencode($item['price']),
    'quantity' => urlencode($item['qty'])
        )
);

the out put is:

array(2) { [0]=> array(9) { ["action"]=> string(4) "SALE" ["type"]=> int(1) ["countryCode"]=> int(826) ["currencyCode"]=> int(826) ["items"]=> array(3) { ["description"]=> string(37) "Product2" ["amount"]=> string(3) "339" ["quantity"]=> string(1) "1" } }

How do it get all products in this array? Any help welcome

Are you asking how to declare a portion of the array statically and then add more items to it?

If so, then the solution is to do exactly that - declare the static portion separartely first and then use your loop to add more things to it. You don't have to declare an entire array in a single statement.

//declare the static portion of the array
$req = array( 
    array(
     'action' => 'SALE',
     'type' => 1,
     'countryCode' => 826,
     'currencyCode' => 826
    ),
    'items' => array()
);

//now add the rest of the data using a loop
foreach ($jcart->get_contents() as $item) {  
  $req['items'][] = array(
    'description' => urlencode($item['name']),
    'amount' => urlencode($item['price']),
    'quantity' => urlencode($item['qty'])
  );
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM