php - 根据数组本身中的值复制数组项
问题描述
我试图通过将它们乘以数组中数量的值来复制数组项。例如,我目前有一个数组,其中有一个数量元素,如下所示:
Array
(
[0] => Array
(
[product_id] => 18551
[quantity] => 1
[text] => 10
[category_id] => 52
)
[1] => Array
(
[product_id] => 15283
[quantity] => 2
[text] => 7
[category_id] => 52
)
[2] => Array
(
[product_id] => 17756
[quantity] => 2
[text] => 7
[category_id] => 49
)
[3] => Array
(
[product_id] => 15026
[quantity] => 1
[text] => 3
[category_id] => 49
)
)
基于上述内容我试图实现的输出将如下所示:
Array
(
[0] => Array
(
[product_id] => 18551
[quantity] => 1
[text] => 10
[category_id] => 52
)
[1] => Array
(
[product_id] => 15283
[quantity] => 1
[text] => 7
[category_id] => 52
)
[2] => Array
(
[product_id] => 15283
[quantity] => 1
[text] => 7
[category_id] => 52
)
[3] => Array
(
[product_id] => 17756
[quantity] => 1
[text] => 7
[category_id] => 49
)
[4] => Array
(
[product_id] => 17756
[quantity] => 1
[text] => 7
[category_id] => 49
)
[5] => Array
(
[product_id] => 15026
[quantity] => 1
[text] => 3
[category_id] => 49
)
)
我的代码如下所示:
foreach ($plants_array as $pa) {
foreach ($pa as $quantity) {
$quantity_array = $pa['quantity'];
}
$new_array[] = $plants_array * $pa['quantity'];
}
但是这会产生以下错误:不支持的操作数类型
阅读此内容表明该错误是因为我正在尝试对数组项进行多重排列,但这正是我试图实现的目标。
有人能指出我如何实现这一目标吗?
感谢您的时间和帮助。
解决方案
我从你的代码中得到了它,它可能不是最有效的,但我认为它有效:
$new_array=[];
foreach ($plants_array as $pa)
{
for($i=0;$i<$pa['quantity'];$i++)
{
$new_array[]=['product_id' =>$pa['product_id'],'quantity' => 1,'text' => $pa['text'],'category_id' => $pa['text']];
}
}
推荐阅读
- javascript - sequelize findAll 不检查当前用户是否喜欢帖子
- javascript - 打印所有行,包括被分页隐藏的行
- c++ - 如何使用函数 std::min() 计算最小值?
- reactjs - Easy-peasy - 无法返回新状态
- mysql - 生成列以在 mysql mariadb 中添加带有计数器的时间戳列
- go - 如何防止递归函数中的死锁?
- c - 如何从 C 中的用户给定数字打印 10 个完美数字?
- sqlite - 删除 sqlite 中的尾随句点
- excel - 根据百分比值在Excel中填充形状?
- .net - .net 互斥体是否应该总是在释放之前释放?