Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Merge arrays in loop

   public function getCheckoutForm(){
   $arr = array(
        'cmd' => '_cart',
        'business' => 'some@mail',
        'no_shipping' => '1',
        'upload' => '1',
        'return' => 'url',
        'cancel_return' => 'url1',
        'no_note' => '1',
        'currency_code' => 'url2',
        'bn' => 'PP-BuyNowBF');

   $cpt=1;
   foreach($this->items as $item){
        $arr1[] = array(
            'item_number_'.$cpt.'' => $item['item_id'],
            'item_name_'.$cpt.'' => $item['item_name'],
            'quantity_'.$cpt.'' => $item['item_q'],
            'amount_'.$cpt.'' => $item['item_price']
            );
        $cpt++;
   }
    return array_merge($arr,$arr1[0],$arr1[1]);
}

This returns array like that:

    Array
(
    [cmd] => _cart
    [business] => some@mail
    [no_shipping] => 1
    [upload] => 1
    [return] => url1
    [cancel_return] =>url2
    [no_note] => 1
    [currency_code] => EUR
    [bn] => PP-BuyNowBF
    [item_number_1] => 28
    [item_name_1] => item_name_1
    [quantity_1] => 1
    [amount_1] => 5
    [item_number_2] => 27
    [item_name_2] => item_name_2
    [quantity_2] => 1
    [amount_2] => 30
)

The problem is that in return $arr1[0] and $arr1[1] are hardcoded. And if in loop i have more than 2 arrays, lets say 0,1,2,3 ans so on, this code won't work. Any idea? Maybe my logic is compleatly wrong...

like image 677
Milen Avatar asked Dec 22 '22 20:12

Milen


2 Answers

There's no need to create arrays in your loop - just add new keys directly to the first array:

public function getCheckoutForm(){
   $arr = array(
        'cmd' => '_cart',
        'business' => 'some@mail',
        'no_shipping' => '1',
        'upload' => '1',
        'return' => 'url',
        'cancel_return' => 'url1',
        'no_note' => '1',
        'currency_code' => 'url2',
        'bn' => 'PP-BuyNowBF'
    );

    $cpt=1;
    foreach($this->items as $item){
        $arr['item_number_'.$cpt] = $item['item_id'];
        $arr['item_name_'.$cpt] = $item['item_name'];
        $arr['quantity_'.$cpt] = $item['item_q'];
        $arr['amount_'.$cpt] = $item['item_price'];
        $cpt++;
    }
    return $arr;
}
like image 156
Cal Avatar answered Jan 14 '23 00:01

Cal


I would probably do something like

$count = count($arr1);
for($i=0;$i<$count;$i++){
     $arr = array_merge($arr,$arr1[$i]);
}
return $arr;
like image 22
eagle12 Avatar answered Jan 14 '23 00:01

eagle12