Php 将数组元素添加到关联数组
我无法找到一种方法来获取数组的元素(产品id)并将它们添加到关联数组的特定键($choices['id]),以便它创建该数组的实例($choices[])与$id中的元素数量相同 我希望$choices[]的最终版本包含与$id[]中元素数量相同的数组 之后,我想对零件号和数量重复此过程Php 将数组元素添加到关联数组,php,arrays,Php,Arrays,我无法找到一种方法来获取数组的元素(产品id)并将它们添加到关联数组的特定键($choices['id]),以便它创建该数组的实例($choices[])与$id中的元素数量相同 我希望$choices[]的最终版本包含与$id[]中元素数量相同的数组 之后,我想对零件号和数量重复此过程 // Create $choices array with keys only $choices = array( 'id' => '', 'part_number' => '',
// 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>";
编辑:
更普遍的解决办法如下:
这可以用于数组创建和插入,因此使用if/else块。为什么不使用id、pn和qty的数组,而不是一个数组中有3个id,另一个数组中有3个pn等等?请您发布您自己的最佳尝试的代码,并指出哪些没有按照您的预期工作?我正在为每个选定的项目收集三条数据(ID,PN,Qty)。@abracadver.谢谢!我想用[1]ID:1,PN:11,22,33)和(Qty:3,2,1)来组织它,而不是用三个字符串来对应数据(ID:1,2,3)(PN:11,3[2]ID:2,PN:22,Qty:2和[3]ID:3,PN:33,数量:1。我愿意以任何方式来组织。是的!谢谢Martyn Shutt。我怀疑foreach循环是解决方案,但我无法正确地将其组合在一起使其工作。太棒了,太快了!谢谢!@JimB814很高兴我能提供帮助。我刚刚发现在下一个数组中重复这一点($part_编号)创建三个新数组,而不是使用相同的三个数组。您可以解决这个问题,还是我应该提交一个新问题?@JimB814我可以通过编辑我的问题来解决它。@JimB814我的编辑应该为您提供一个可重用的解决方案。
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' => '',
);
}
}