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' => 开发者_如何学Go5),
array(
'id'=> 4,
'qty' => 7
)
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]);
}
Also one-liner w/ lambda (PHP >= 5.3.0) and short array syntax []
(PHP >= 5.4)
$combined = array_map(function($id, $qty) {return ['id' => $id, 'qty' => $qty];}, $id, $qty);
or callback and old array()
for earlier versions
function comb($id, $qty)
{
return array('id' => $id, 'qty' => $qty);
}
$combined = array_map('comb', $id, $qty);
精彩评论