将数组元素添加到关联数组
问题描述:
我无法找到一种方法来获取数组(元素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块。
为什么不有一个数组有id,pn和qty而不是3个id在另一个中,而3个pn在另一个中......? – AbraCadaver
您能否请您发布自己最佳尝试的代码,并指出哪些工作不符合您的预期? – rodamn
我正在收集每个选定项目(ID,PN,Qty)的三个数据。 @AbraCadaver。谢谢!而不是三个具有相应数据(ID:1,2,3)(PN:11,22,33)和(Qty:3,2,1)的字符串,我想这样组织它:[1] ID:1 ,PN:11,数量:3 [2] ID:2,PN:22,数量:2和[3] ID:3,PN:33,数量:1。我乐意以任何方式组织这一点。 – JimB814