首页 > 解决方案 > 关联数组PHP中的ForEach循环

问题描述

我有以下 foreach 循环

$selectedids = "1255;1256;1257";
$selectedidsarr = explode(';', $selectedids);
$idstand = '1';
foreach ($selectedidsarr as $item) {

    $output1 = $idstand++;
    echo "<li>product_id_$output1 = $item,</li>";
}


我想在下面的关联数组中添加上述循环的输出

          $paramas = array(
                'loginId' => $cred1,
                'password' => $credpass1,
                'orderId' =>    $orderid,
                'offer' => $offerid,
                'shipid' => $shipcharge
)

这样最终的数组将如下所示;

          $paramas = array(
                'loginId' => $cred1,
                'password' => $credpass1,
                'orderId' =>    $orderid,
                'offer' => $offerid,
                'shipid' => $shipcharge,
                'product1_id' => 1255,
                'product2_id' => 1256,
                'product3_id' => 1257,
)

我尝试创建以下解决方案,但它不适合我

$selectedids = $boughtitem;
$selectedidsarr = explode(';', $selectedids);
$idstand = '1';

foreach ($selectedidsarr as $item) {
    $idoutput1 = $idstand++;
    $paramas [] = array (  
    'product$idoutput1_id' => $item,
        );
}

需要建议。

标签: phparrays

解决方案


您不需要定义新数组,只需将当前数组的键设置为您想要的值,$array[$key] = $value以获取看起来像的数组的形式[$key=>$value],或者在您的情况下......

$paramas['product' . $idoutput1 . '_id'] = $item;

推荐阅读