Wednesday, 1 October 2014

convert index array to associative array

I have an array like
$products = array(array(354),array(1),array(375),array(1),array(344),array(2));
and i want to achieve array like that

$arrProducts= array(array('product_id'=>354,'qty'=>1),array('product_id'=>375,'qty'=>1),array('product_id'=>344,'qty'=>2));


Answer1:
You can use array_chunk in this case if this is always by twos, and combine it with array_combine():

$products = array(array(354),array(1),array(375),array(1),array(344),array(2));
$products = array_chunk($products, 2);

$arrProducts = array();
$keys = array('product_id', 'qty');
foreach($products as $val) {
    $arrProducts[] = array_combine($keys, array(reset($val[0]), reset($val[1])));
}

echo '<pre>';
print_r($arrProducts);


Answer2:
Consume two array elements on each iteration:

$arrProducts = array();
$inputLength = count($products);
for ($i = 0; $i < $inputLength; $i += 2) {
    $arrProducts[] = array('product_id' => $products[$i][0], 'qty' => $products[$i+1][0]);
}

0 comments:

Post a Comment