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...

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;
}

Need Your Help

Get the contents of a line by line number in perl, awk, grep

perl sed awk grep

I would like to know if it's possible to get contents of line by line number as input. For example how can I get the contents of line 314 using a tool such as perl, grep, awk.

Error: Singular Matrix

python python-2.7 matrix equation-solving

I'm having an error in my code, I hope you can help me!:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.