2015-09-04 124 views
0

我无法找到一种方法来获取数组(元素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'); 
+1

为什么不有一个数组有id,pn和qty而不是3个id在另一个中,而3个pn在另一个中......? – AbraCadaver

+0

您能否请您发布自己最佳尝试的代码,并指出哪些工作不符合您的预期? – rodamn

+0

我正在收集每个选定项目(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

回答

0

如果我正确理解你的问题,你的意思是这样的?

$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块。

+0

是的!感谢Martyn Shutt。我怀疑foreach循环是解决方案,但我无法正确地将它放在一起以使其工作。神奇而快速!谢谢! – JimB814

+0

@ JimB814很高兴我能帮上忙。 –

+0

我刚刚发现,为下一个数组($ part_numbers)重复此操作将创建三个新数组,而不是使用相同的三个数组。你能解决这个问题,还是应该提交一个新的问题? – JimB814