Showing posts with label PHP array_chunk. Show all posts
Showing posts with label PHP array_chunk. Show all posts

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

Wednesday, 24 September 2014

array_chunk in PHP

Using PHP array_chunk() function an array is divided into chunks of new arrays.
PHP Array chunk breaks an array into multidimensional array with existent array’s values.

Syntax:  array_chunk(array,size,preserve_key)

Parameters Description:
array : Required. Specifies the array  to use
size : Required. Specifies how many elements each new array will contain
preserve_key : Optional. Possible values:

  • true - Preserves the keys from the original array.
  • false - Default. Does not preserve the keys from the original array.
Example:
<?php
$days = array( "a"=>"Sunday","b"=>"Monday","c"=>"Tuesday","d"=>"Wednesday");
print_r( array_chunk($days,2) );
echo "<br />";
print_r(array_chunk($days,2,true) );
?>
Output:
Array (
           [0] => Array ( 
                                [0] => Sunday
                                [1] => Monday 
                              )
           [1] => Array (
                                [0] => Tuesday
                                [1] => Wednesday 
                              )
          )
Array ( 
          [0] => Array (
                               [a] => Sunday
                               [b] => Monday
                             ) 
          [1] => Array ( 
                               [c] => Tuesday
                               [d] => Wednesday 
                              ) 
         )