Skip to content
Advertisement

php how to put foreach loop value in array

i want to put foreach in values in array to assign value as loop in array. how to do that? i try put foreach inside array but looks like its wrong.

my array code:

$allcart[] = $_SESSION["shopping_cart"];

if i print i will get this value

Array ( [0] => Array ( [item_varid] => 109 [item_id] => 146 [item_basename] => aaa [item_baselink] => products.php?id=146 [item_name] => grey [item_price] => 10 [item_image] => Upload20220224569751018.jpg [item_totalquan] => 120 [item_quantity] => 2 ) [1] => Array ( [item_varid] => 110 [item_id] => 146 [item_basename] => aaa [item_baselink] => products.php?id=146 [item_name] => pink [item_price] => 20 [item_image] => Upload20220224569794304.png [item_totalquan] => 130 [item_quantity] => 4 ) [2] => Array ( [item_varid] => 111 [item_id] => 146 [item_basename] => aaa [item_baselink] => products.php?id=146 [item_name] => yellow [item_price] => 30 [item_image] => Upload20220224731849169.jpg [item_totalquan] => 230 [item_quantity] => 5 ) )

i want put in this $allcart array inside this one

function payPal(array $allcart,$gateway){

try {
            
            $response = $gateway->purchase(array(
                'amount' => $totalprice,
                //
            'items' => array(
                    array(
                        //put below here, replace 'name' value with array value [item_basename] from $allcart
                        'name' => 'Course Subscription',
                        'price' => $_POST['amount'],
                        'description' => 'Get access to premium courses.',
                        'quantity' => 1
                    ),
                ),
                //
                'currency' => PAYPAL_CURRENCY,
                'returnUrl' => PAYPAL_RETURN_URL,
                'cancelUrl' => PAYPAL_CANCEL_URL,
                


            ))->send();
}

Advertisement

Answer

function payPal(array $allcart,$gateway){

try {
            foreach ($allcart as $key => $value) {
                    $items[] = array('name' => $value['item_basename'],
                              'price' => $value['item_price'],
                              'description' => 'Get access to premium courses.',
                              'quantity' => $value['item_quantity'] 
               );
               }
            
            $response = $gateway->purchase(array(
                'amount' => $totalprice,
                'items' => $items,
                'currency' => PAYPAL_CURRENCY,
                'returnUrl' => PAYPAL_RETURN_URL,
                'cancelUrl' => PAYPAL_CANCEL_URL,
            ))->send();
}

I hope this will solve your query as i stored all your $allcart array into new $items array and called.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement