0

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?

3 Answers 3

10

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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

1 Comment

This is how I'd do it. No need to overcomplicate things.
1
$i=1;
$j=0;
foreach($products as $val)
{
if(($i%2) == 0) 
{       
  $abc[$j]['qty'] =$val[0];
  $j++;
}
else
{
 $abc[$j]['product_id'] =$val[0];   
}
$i++;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.