php - 关联数组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,
);
}
需要建议。
解决方案
您不需要定义新数组,只需将当前数组的键设置为您想要的值,$array[$key] = $value
以获取看起来像的数组的形式[$key=>$value]
,或者在您的情况下......
$paramas['product' . $idoutput1 . '_id'] = $item;
推荐阅读
- html - XML 和 XSL 文件输出为 HTML 文件
- c++ - 短读错误-Boost asio同步https调用
- java - 如何在多模块 Maven 项目的子模块中禁用某些强制执行规则?
- c# - 在关联来自不同基类的派生类时避免双向依赖
- memory - 什么是 Rust 取消提交并将内存返回给操作系统的策略?
- python - Python 中的自定义 For 循环
- flutter - 在 android 模拟器中无法访问 localhost:portnumber
- java - 布尔方法返回表达式未在输出控制台中显示结果
- c - 在C中打印带有6个字符的负十六进制
- android - recyclerView 中的过滤列表