开发者

Using foreach inside of a defined array PHP

Is there anyway to loop through an array and insert each instance into another array?

   $aFormData = array(
        'x_show_form' => 'PAYMENT_FORM',
        foreach($aCartInfo['items'] as $item){
            'x_line_item' => $item['id'].'<|>'.$item['title'].'<|>'.$item['description'].'<|>'.$item['quantity'].'<|>'.$item['price'].'<|&g开发者_运维问答t;N',
        }

    );


Not directly in the array declaration, but you could do the following:

$aFormData = array(
    'x_show_form' => 'PAYMENT_FORM',
    'x_line_item' => array(),
);
foreach($aCartInfo['items'] as $item){
    $aFormData['x_line_item'][] = $item['id'].'<|>'.$item['title'].'<|>'.$item['description'].'<|>'.$item['quantity'].'<|>'.$item['price'].'<|>N';
}


Yes, there is a way ; but you must go in two steps :

  • First, create your array with the static data
  • And, then, dynamically add more data


In your case, you'd use something like this, I suppose :

$aFormData = array(
   'x_show_form' => 'PAYMENT_FORM',
   'x_line_item' => array(),  // right now, initialize this item to an empty array
);

foreach($aCartInfo['items'] as $item){
    // Add the dynamic value based on the current item
    // at the end of $aFormData['x_line_item']
    $aFormData['x_line_item'][] = $item['id'] . '<|>' . $item['title'] . '<|>' . $item['description'] . '<|>' . $item['quantity'] . '<|>' . $item['price'] . '<|>N';
}


And, of course, you should read the section of the manual that deals with arrays : it'll probably help you a lot ;-)


You mean something like this :

$aFormData = array(
    'x_show_form' => 'PAYMENT_FORM',
    'x_line_item' => array(),
);

foreach($aCartInfo['items'] as $item) {
     $aFormData['x_line_item'][] = implode('<|>', $aCartInfo['items']).'<|>N',
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜