简体   繁体   中英

Add array elements to associative array

I am unable to find a way to take the elements of an array (product IDs) and add them to a particular key of an associative array ($choices['id]) so that it creates as many instances of that array ($choices[ ]) as there are elements in $id.

I want the final version of $choices[ ] to include as many arrays as there are elements in $id[ ].

After that I want to repeat this process for part_numbers & quantity.

// 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');

If I'm understanding your question correctly, you mean something like this?

$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>";

Output:

 Array (
    [0] => Array
        (
            [id] => 181
            [part_number] => 
            [quantity] => 
        )

    [1] => Array
        (
            [id] => 33
            [part_number] => 
            [quantity] => 
        )

    [2] => Array
        (
            [id] => 34
            [part_number] => 
            [quantity] => 
        )

)

Edit:

A more general solution would be as follows:

$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' => '',
    );
   }
} 

This can be used for array creation and insertion, hence the if/else block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM