Lokesh Jain Lokesh Jain - 20 days ago 5
PHP Question

how to convert index array to associative array?

I have an array like that

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


I achieved this array using this code

foreach($products as $val)
{
$abc[] =$val[0];

}

for($i=0;$i<count($abc);$i++)
{
if($i%2==0)
{
$newarr[]['product_id'] = $abc[$i];
}
else{
$newarr[]['qty'] = $abc[$i];
}
}


for($j=0;$j<count($newarr);$j++)
{
if($j%2==0)
{
$arrProducts[] = array_merge($newarr[$j],$newarr[$j+1]);
}
else{
continue;
}
}

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


but i think my way to get this array is too long so how can i get this array in short way using some array functions or should i use this code?

Answer

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

Another alternative would be:

$products = array(array(354),array(1),array(375),array(1),array(344),array(2));
$keys = array('product_id', 'qty');
$arrProducts = array_map(function($e) use ($keys) {
    return array_combine($keys, array_map('reset', $e));
}, array_chunk($products, 2));

This will yield the same result.