我无法找到一种方法来获取数组(产品id)的元素并将它们添加到关联数组($choices['id])的特定键,以便它创建该数组($choices[])的尽可能多的实例,因为有$id中的元素。
我希望$choices[]的最终版本包含与$id[]中的元素一样多的数组。
之后,我想对part_numbers &数量。
// Create $choices array with keys only
$choices = array(
'id' => '',
'part_number' => '',
'quantity' => '',
);
// Insert $id array values into 'id' key of $choices[]
$id = array('181', '33', '34');
如果我正确理解了你的问题,你是指像这样的东西吗?
$choices = array();
$id = array('181', '33', '34');
foreach($id as $element)
{
$choices[] = array(
'id' => $element,
'part_number' => '',
'quantity' => '',
);
}
echo "<pre>";
print_r($choices);
echo "</pre>";
输出: Array (
[0] => Array
(
[id] => 181
[part_number] =>
[quantity] =>
)
[1] => Array
(
[id] => 33
[part_number] =>
[quantity] =>
)
[2] => Array
(
[id] => 34
[part_number] =>
[quantity] =>
)
)
编辑:更一般的解决方案如下:
$choices = array();
$values = array('sku-123', 'sku-132', 'sku-1323');
foreach($values as $i => $value){
if(array_key_exists($i, $choices))
{
$choices[$i]['part_number'] = $value;
}
else
{
$choices[] = array(
'id' => '',
'part_number' => $value,
'quantity' => '',
);
}
}
可用于数组的创建和插入,因此有if/else块。