Search code examples
phparraysassociative

how combine multiple arrays into a single associate array using the arrays as keys


I have 2 arrays that i would like to loop through and combine into an associative array. I would like to use the 2 arrays as the keys for the new associative array. I am new to php so any and all help would be appreciated.

$id = array( 2, 4);

$qty = array( 5, 7);

array('id' => , 'qty' => );

Thanks in advance

I would like to output something like this

array(
'id' => 2,
'qty' => 5),
array(
'id'=> 4,
'qty' => 7
)

Solution

  • You can do:

    $result = array();
    
    for($i=0;$i<count($id);$i++) {
      $result[] = array('id' => $id[$i], 'qty' => $qty[$i]);
    }
    

    Added by Mchl: Alternative, IMHO a bit clearer, but it's matter of opinion mostly

    $result = array();
    
    foreach($id as $key => $value) {
      $result[] = array('id' => $id[$key], 'qty' => $qty[$key]);
    }