creating a array with index value dynamically in php

592 Views Asked by At

hi i want to create an array dynamically with the index value and the key value.

here $head is the array name and $values is the key value

$head = Array ( [0] => Dis_id [1] => Dis_Desc [2] => Dis_Per [3] => Dis_val ) 
$values = Array ([0] => Dl-Dis1  [1] => Discount [2] => 7.500 [3] => 26.25 ) 
          Array ([0] => Dl-Dis2 [1] => Discount [2] => 2.500 [3] => 73.13 )

foreach($values as $valu => $key)
       {
         $value = $value + array($head[$valu]=>$key.",");
       }
echo '<pre>';
print_r($value);

The output will be as

 Array
(
[Dis_id] => Dl-Dis2,
[Dis_Desc] => Discount,
[Dis_Per] => 2.500,
[Dis_val] => 73.13,
)

But the output i need is as follows

Array
(
[Dis_id] => Dl-Dis1,
[Dis_Desc] => Discount,
[Dis_Per] => 7.500,
[Dis_val] => 26.25,
)    
Array
(
[Dis_id] => Dl-Dis2,
[Dis_Desc] => Discount,
[Dis_Per] => 2.500,
[Dis_val] => 73.13,
)

i dont know how to do please help me

update to get my output

$values = array(array (0 => 'Dl-Dis1',  1 => 'Discount', 2 => 7.500, 3 => 26.25 ), array (0 => 'Dl-Dis2', 1 => 'Discount', 2 => 2.500, 3 => 73.13 )) ;

thank u all

2

There are 2 best solutions below

4
On BEST ANSWER

You may need to use array_combine. While under the loop, combine the $head and the values itself to it and put it inside a new container. Consider this example:

$head = Array ( 0 => 'Dis_id', 1 => 'Dis_Desc', 2 => 'Dis_Per', 3 => 'Dis_val', );
$values = array(array (0 => 'Dl-Dis1',  1 => 'Discount', 2 => 7.500, 3 => 26.25 ), array (0 => 'Dl-Dis2', 1 => 'Discount', 2 => 2.500, 3 => 73.13 )) ;

$new_values = array();
foreach($values as $value) {
    $new_values[] = array_combine($head, $value);
}

Sample Output

0
On

You can do it like this:

$head = array ( 0 => 'Dis_id',  1 => 'Dis_Desc', 2 => 'Dis_Per', 3 => 'Dis_val' );
$values = array(array (0 => 'Dl-Dis1',  1 => 'Discount', 2 => '7.500', 3 => 26.25 ),
      array (0 => 'Dl-Dis2', 1 => 'Discount', 2 => 2.500, 3 => 73.13 ));
$result = array();
foreach($values as $value) {
    $res = array();
    foreach ($value as $key => $val) {
        $res[$head[$key]] = $val;
    }
    $result[] = $res;
}
echo '<pre>';
print_r($result);