PHP - Sum of array values based on key - php

Below is the array output which shows user data, month wise. I need to get the sum of ACTUAL_HOURS for different resources.
For below, sum of ACTUAL_HOURS for User 1 and User 2 for the month JUL-2015, should be 10 + 20 = 30.
Same goes for AUG-2015 which is 80 + 20 = 100
$user_array output
Array
(
[User 1] => Array
(
[JUL-2015] => Array
(
[SITE_STATUS] => Offshore
[ACTUAL_HOURS] => 10
[PROJECTED_HOURS] => 20
)
[AUG-2015] => Array
(
[SITE_STATUS] => Offshore
[ACTUAL_HOURS] => 80
[PROJECTED_HOURS] => 88
)
)
[User 2] => Array
(
[JUL-2015] => Array
(
[SITE_STATUS] => Offshore
[ACTUAL_HOURS] => 20
[PROJECTED_HOURS] => 0
)
[AUG-2015] => Array
(
[SITE_STATUS] => Offshore
[ACTUAL_HOURS] => 20
[PROJECTED_HOURS] => 0
)
)
)
$project_months output
Array
(
[0] => JUL-2015
[1] => AUG-2015
)
Looping the data like below gives summation but not for User 1
foreach ($user_array as $user_name => $user_data) {
foreach ($project_months as $month) {
}
}
How do I show summation of ACTUAL_HOURS or PROJECTED_HOURS for different resource month wise as shown above ?

You can simply use two foreach loops.
$hoursInMonth = array();
foreach ($users as $user)
{
foreach ($user as $month => $userData) {
$hoursInMonth[$month] += $userData['ACTUAL_HOURS'];
}
}
Considering the $users variable is the array from the question, this yields the following result:
Array
(
[JUL-2015] => 30
[AUG-2015] => 100
)
You could wrap it in a function, so you can easily switch between the desired index.
/**
* #param array $inputArray The input array
* #param string $typeOfHours The desired index
* #return array
*/
function calculateHoursInMonths(array $inputArray, $typeOfHours)
{
$hoursInMonth = array();
foreach ($inputArray as $user)
{
foreach ($user as $month => $userData) {
$hoursInMonth[$month] += $userData[$typeOfHours];
}
}
return $hoursInMonth;
}
Note, this does not take in consideration the Offshore/Onshore state. You can add that by adding a simple if.

You are doing it wrong. There is no need for two nested foreach loops. You just need a for loop to loop through project months and a foreach loop to loop through users array.
You did not shared the array in php code, but I assume you are array is as below:
$array = array(
'User 1' => array(
'JUL-2015' => array(
'SITES_STATUS' => 'Offshore',
'ACTUAL_HOURS' => 10,
'PROJECTED_HOURS' => 20
),
'AUG-2015' => array(
'SITES_STATUS' => 'Offshore',
'ACTUAL_HOURS' => 80,
'PROJECTED_HOURS' => 88
),
),
'User 2' => array(
'JUL-2015' => array(
'SITES_STATUS' => 'Offshore',
'ACTUAL_HOURS' => 20,
'PROJECTED_HOURS' => 0
),
'AUG-2015' => array(
'SITES_STATUS' => 'Offshore',
'ACTUAL_HOURS' => 20,
'PROJECTED_HOURS' => 0
),
),
);
And months are below:
$project_months = array('JUL-2015', 'AUG-2015');
Now to calculate total actual hours for all users for each month, you will need loops like below:
for ($i=0; $i < count($project_months); $i++) {
$totalActualHours = 0;
foreach($array AS $ar) {
$totalActualHours += $ar[$project_months[$i]]['ACTUAL_HOURS'];
}
echo $project_months[$i].': '.$totalActualHours.'<br>';
}
The output of this code when run for ACTUAL_HOURS:
JUL-2015: 30
AUG-2015: 100
Hope this will help.

Related

Average result of multidimensional array in PHP

This is a question for all the array specialists out there. I have an multi dimension array with a result as number (can be 0,1 or 2) and need the average for each grouped by parent.
In the example below the calculation would be:
subentry1_sub1 = 2 + 2 = 4 (4/2=2)
subentry1_sub2 = 1 + 1 = 2 (2/2=1)
So what I try to archive in PHP is the following result:
subentry1_sub1 average = 2
subentry1_sub2 average = 1
...
I already tried some solutions from similar questions. But with all the recursive functions I didn't managed to get it aggregated by the last child name (e.g. subentry1_sub1).
Any ideas?
EDIT:
subentry1_sub1 is 2 + 2 because its two times in the array
[entry1] => [subentry1] => [subentry1_sub1] => result
[entry2] => [subentry1] => [subentry1_sub1] => result
Array
(
[entry1] => Array
(
[subentry1] => Array
(
[subentry1_sub1] => Array
(
[value] => abc
[result] => 2
)
[subentry1_sub2] => Array
(
[value] => abc
[result] => 1
)
)
[subentry2] => Array
(
[subentry2_sub1] => Array
(
[value] => abc
[result] => 1
)
[subentry2_sub2] => Array
(
[value] => abc
[result] => 1
)
)
)
[entry2] => Array
(
[subentry1] => Array
(
[subentry1_sub1] => Array
(
[value] => abc
[result] => 2
)
[subentry1_sub2] => Array
(
[value] => abc
[result] => 1
)
)
[subentry2] => Array
(
[subentry2_sub1] => Array
(
[value] => abc
[result] => 1
)
[subentry2_sub2] => Array
(
[value] => abc
[result] => 1
)
)
)
)
Try this code. In this i have created a new array $sum which will add result value of same subentry childs with same key and another array $count which will count the number of times each key repeats
<?php
$data = array('entry1'=>array(
'subentry1'=>
array(
'subentry1_sub1'=>array('value'=>'abc','result'=>2),
'subentry1_sub2'=>array('value'=>'abc','result'=>1)
),
'subentry2'=>
array(
'subentry2_sub1'=>array('value'=>'abc','result'=>1),
'subentry2_sub2'=>array('value'=>'abc','result'=>1)
)
),
'entry2'=>array(
'subentry1'=>
array(
'subentry1_sub1'=>array('value'=>'abc','result'=>2),
'subentry1_sub2'=>array('value'=>'abc','result'=>1)
),
'subentry2'=>
array(
'subentry2_sub1'=>array('value'=>'abc','result'=>1),
'subentry2_sub2'=>array('value'=>'abc','result'=>1)
)
)
);
$sum = array();
$repeat = array();
foreach($data as $input){
foreach($input as $array){
foreach($array as $key=>$value){
if(array_key_exists($key,$sum)){
$repeat[$key] = $repeat[$key]+1;
$sum[$key] = $sum[$key] + $value['result'];
}else{
$repeat[$key] = 1;
$sum[$key] = $value['result'];
}}}}
echo "<pre>";
print_r($sum);
print_r($repeat);
foreach($sum as $key=>$value){
echo $key. ' Average = '. $value/$repeat[$key]."</br>";
}
Output
Array
(
[subentry1_sub1] => 4
[subentry1_sub2] => 2
[subentry2_sub1] => 2
[subentry2_sub2] => 2
)
Array
(
[subentry1_sub1] => 2
[subentry1_sub2] => 2
[subentry2_sub1] => 2
[subentry2_sub2] => 2
)
subentry1_sub1 Average = 2
subentry1_sub2 Average = 1
subentry2_sub1 Average = 1
subentry2_sub2 Average = 1
You can easily calculate avg now
Note : As you mentioned you are counting occurence of subentry1_sub1 etc so i did the same so it will also count whether key result exists or not
I know this is an old thread but im pretty sure there is a much easier way of doing this for anyone who is interested:
If you know the result will always be a number:
foreach($my_array as $entry_name => $entry_data)
{
foreach($entry_data as $sub_name => $sub_data)
{
$sub_results = array_column($sub_data, 'result');
$averages[$entry_name][$sub_name] = array_sum($sub_results)/count($sub_results);
}
}
If its possible the result could be NULL or empty, this will check it and return 'N/A' if there is no valid data to calculate an average from:
foreach($my_array as $entry_name => $entry_data)
{
foreach($entry_data as $sub_name => $sub_data)
{
$sub_results = array_filter(array_column($sub_data, 'result'));
$averages[$entry_name][$sub_name] = (count($sub_results) > 0 ? array_sum($sub_results)/count($sub_results) : 'N/A');
}
}
both of these solutions will give you an averages array that will output the average per subentry per entry.
Try this like,
<?php
$data=array('entry1'=>array(
'subentry1'=>
array(
'subentry1_sub1'=>array('value'=>'abc','result'=>3),
'subentry1_sub2'=>array('value'=>'abc','result'=>3)
),
'subentry2'=>
array(
'subentry2_sub1'=>array('value'=>'abc','result'=>2),
'subentry2_sub2'=>array('value'=>'abc','result'=>8)
)
),
'entry2'=>array(
'subentry1'=>
array(
'subentry1_sub1'=>array('value'=>'abc','result'=>6),
'subentry1_sub2'=>array('value'=>'abc','result'=>6)
),
'subentry2'=>
array(
'subentry2_sub1'=>array('value'=>'abc','result'=>10),
'subentry2_sub2'=>array('value'=>'abc','result'=>12)
)
)
);
foreach($data as $k=>$v){
echo "----------------$k---------------------\n";
if(is_array($v)){
foreach($v as $a=>$b){
if(is_array($b)){
echo $a.' average = ';
$c=array_keys($b);// now get *_sub*
$v1=isset($b[$c[0]]['result']) ? $b[$c[0]]['result'] : '';
$v2=isset($b[$c[1]]['result']) ? $b[$c[1]]['result'] : '';
echo ($v1+$v2)/2;
echo "\n";
}
}
}
}
Online Demo
In the meantime I found a simple working solution myself:
foreach ($data as $level2) {
foreach ($level2 as $level3) {
foreach ($level3 as $keyp => $level4) {
foreach ($level4 as $key => $value) {
if($key == 'result') $stats[$keyp] += $value;
}
}
}
}
With that you get the total for every key in an new array $stats.
But be sure to checkout the solution from user1234, too. It's working great and already includes the calculation of the average.
https://stackoverflow.com/a/39292593/2466703

PHP - Conditioned sum of some values of an array

I have an array in PHP of this type, resulting from a particular query on a db.
$output = Array
(
[0] => Array
(
'price' => 100
'date' => '2015-07-28'
'total' => 200
'qty' => 2
)
[1] => Array
(
'price' => 80
'date' => '2015-07-28'
'total' => 240
'qty' => 3
)
[2] => Array
(
'price' => 100
'date' => '2015-07-29'
'total' => 300
'qty' => 3
)
[3] => Array
(
'price' => 90
'date' => '2015-07-28'
'total' => 90
'qty' => 1
)
)
I'm trying to sum total and qty based on price key values, obtaining an array that will look like this:
$grouped = Array
(
[0] => Array
(
[price] => 100
[sumtotal] => 500
[sumqty] => 5
)
[1] => Array
(
[price] => 80
[sumtotal] => 240
[sumqty] => 3
)
[2] => Array
(
[price] => 90
[sumtotal] => 90
[sumqty] => 1
)
)
Still cannot find a way to get around this.
Try using simple foreach loop as
$result = array();
foreach ($output as $key => $value) {
$hash = $value['price'];
if (isset($result[$hash])) {
$result[$hash]['price'] = $value['price'];
$result[$hash]['sumtotal'] += $value['total'];
$result[$hash]['sumqty'] += $value['qty'];
} else {
$result[$hash]['price'] = $value['price'];
$result[$hash]['sumtotal'] = $value['total'];
$result[$hash]['sumqty'] = $value['qty'];
}
}
print_r(array_values($result));
Demo
I don't understand, it's the same array without the date.. ?
Edit :
Ok try this
$temp= array();
for($i=0; $i<sizeof($outpout);$i++)
{
if(!isset($temp[$i]))
$temp[$i]=array();
$temp[$i][$outpout[$i]['price']]+=$outpout[$i]['qty']];
}
$res=array();
$count=0;
foreach($temp as $key => $value)
{
$res[$count]['price']=$key;
$res[$count]['qty']=$value;
$res[$count]['total']=$key*$value;
$count++;
}
Okay, here's a simple complete code to solve your problem.
$output=array();//this is your array
$price_index=array();
$final_array=array();
foreach($output as $key=>$value)
{
//first check if price is already in $price_index
if(!isset($price_index[$value["price"]]))
{
$price_index[$value["price"]]=sizeof($price_index);
}
$final_index=$price_index[$value["price"]];
if(isset($final_array[$final_index]))
{
$final_array[$final_index]["total"]+=$value["total"];
$final_array[$final_index]["qty"]+=$value["qty"];
}
else
{
$final_array[$final_index]["total"]=$value["total"];
$final_array[$final_index]["qty"]=$value["qty"];
$final_array[$final_index]["price"]=$value["price"];
}
}
//display our final array
print_r($final_array);
What I did:
iterate through your array
check if the current price has been added to $final_array before, by creating $price_index array that contains price as key and the value is the index of $output array on the first time the price occurred.
now if the price occur again, the $price_index[current price] will be detected that it is already been set before, then we will use the value as the index of our $final_array and add the current total and qty to existing.
then display the array (optional).
Hope it helps. Please don't just copy my code, analyze and understand it mate :)

How To Make Nesting Array From Existing Array in php

What I Need
i Need to create nesting array from existing array.
if in array both values type are same .
group according their type.
like array[1] type is same array[2] type so i need to group them in single nested array.
here is the array structure
$data=$event['data']['pricing_detail'];
[1] => Array
(
[type] => General Public Tickets Adult
[amount] => 50
[comment] => (Working Days)
)
[2] => Array
(
[type] => General Public Tickets Adult
[amount] => 80
[comment] => (Saturday/ Sunday/ Holiday)
)
i need output like
[1] => Array
(
[type] => General Public Tickets Adult
[metadata]=>array
(
[0] =>array
(
[amount] => 50
[comment] => (Working Days)
)
[1]=>array
(
[amount] => 80
[comment] => (Saturday/ Sunday/ Holiday)
)
)
)
code snippet
$data=$event['data']['pricing_detail'];
$metadata = array();
foreach($data as $key => $value)
{
if($value[1]['type'] == $value[2]['type'])
{
$metadata[$key]['amount'] = $value['amount'];
print_r($metadata);
}
else
{
echo "not matched";
}
}
Problem im facing im not able to make logic so to get desired result.
Loop your array, storing the types and the array they belong to.
Then loop the types and add te values.
//store types and the arrays the belong to
foreach($data as $k=>$v){
$type[$v['type']][]=$k;
}
//loop types, creating result array
foreach($type as $k=>$v){
$tmp=array(
'type'=>$k,
'metadata'=>array()
);
//loop all the arrays of this type
foreach($v as $w){
//store in TMP
$t=array(
'amount' => $vals[$w]['amount'],
'comment' => $vals[$w]['comment']
);
//sort TMP on EMPTY value
usort($t,function ($a, $b) {
if($a == '' && $b != '') return 1;
if($b == '' && $a != '') return -1;
if($b == 0){return 1;}
return 0;
});
//store
$tmp['metadata'][]=$t;
}
$result[]=$tmp;
}
echo '<pre>'.print_r($result,true).'<pre>';
Example:
$data=array(
1 => Array(
'type' => 'General Public Tickets Adult',
'amount' => 50,
'comment' => '(Working Days)'),
2 => Array (
'type' => 'General Public Tickets Adult',
'amount' => 80,
'comment' => '(Saturday/ Sunday/ Holiday)'),
3 => Array (
'type' => 'Special Tickets Children',
'amount' => 300,
'comment' => '(Saturday/ Sunday/ Holiday)'),
4 => Array (
'type' => 'Special Tickets Children',
'amount' => 10000,
'comment' => '(Monday afternoon)')
);
result:
Array
(
[0] => Array(
[type] => General Public Tickets Adult
[metadata] => Array(
[0] => Array(
[amount] => 50
[comment] => (Working Days)
)
[1] => Array(
[amount] => 80
[comment] => (Saturday/ Sunday/ Holiday)
)
)
)
[1] => Array(
[type] => Special Tickets Children
[metadata] => Array(
[0] => Array(
[amount] => 300
[comment] => (Saturday/ Sunday/ Holiday)
)
[1] => Array(
[amount] => 10000
[comment] => (Monday afternoon)
)
)
)
)
[edit] updated with usort for sorting empty 'comments';
[edit] added line to usort to prevent unwanted sorting when tickets = 0;
And a fiddle
You have too create a new tickets array, with first dimention being the contents of type and second dimension being it's original id.
Something like this:
$grouped = array();
foreach($data as $key => $value) {
$grouped[$value['type']][$key] = $value;
unset($grouped[$value['type']][$key]["type"]);
}
print_r($grouped);
Adjust according to your array structure, I cant see the your actual structure of $data in your samples.
If you want to sort a multilevel array, you can use a variation of this function:
/**
* sort an multidimensional array by any of it's fields and return sorted array
* ex.: $sorted = multisort($data, 'volume', SORT_DESC, 'edition', SORT_ASC);
* IMPORTANT: This function uses mutlisort and will reindex numeric keys !
* #param array $data array to sort
* #param string $field name of field to sort by
* #param int $direction SORT_DESC or SORT_ASC constant
* #return array
*/
function multisort(){
$args = func_get_args();
$data = array_shift($args);
foreach ($args as $n => $field) {
if (is_string($field)) {
$tmp = array();
foreach ($data as $key => $row)
$tmp[$key] = $row[$field];
$args[$n] = $tmp;
}
}
$args[] = &$data;
call_user_func_array('array_multisort', $args);
return array_pop($args);
}
Used like this:
foreach($grouped as $type => &$list)
$list = multisort($list, 'comment', SORT_DESC);

How to correctly convert an array in PHP with quantity/price data?

I can't seem to wrap my head around this.
I am given an array in PHP that looks something like this:
array (
0 => array (
0 => 50,
1 => 0.80
),
1 => array (
0 => 300,
1 => 0.50
),
2 => array (
0 => 600,
1 => 0.30
),
3 => array (
0 => 1000,
1 => 0.20
),
4 => array (
0 => 4000,
1 => 0.10
)
);
An array of arrays where the first index of the inner array represents a quantity while the second index represents a price.
I want to import this data into my database, but in a specific way.
I have specific quantities that I like to keep track of that are defined by the following array:
array(10,100,500,1000,5000,10000);
I then want to make the original array more fine tuned to quantities and prices that I would like to see. So in this particular example, I would like an array that looks like this:
array (
0 => array (
0 => 100,
1 => 0.80
),
1 => array (
0 => 500,
1 => 0.50
),
2 => array (
0 => 1000,
1 => 0.20
),
3 => array (
0 => 5000,
1 => 0.10
)
);
My new array will only contain the specific quantity indexes.
If a quantity exists in the original array, I use that price. If it doesn't exist, I would use the price of the next lowest quantity. If no lower quantity exists, I don't want to see that quantity in the new array.
I have been able to accomplish what I want for the most part with the following code:
function getRelativePrices($pricearray) {
$relativeprices = array();
$types = array(10,100,500,1000,5000,10000);
foreach ($types as $q) {
$new_array = array();
foreach ($pricearray as $index => $array) {
if ($q >= $array[0]) {
$new_array = array($q, $array[1]);
}
}
if (sizeof($new_array)) {
$relativeprices[] = $new_array;
}
}
return $relativeprices;
}
The only problem with the above is that I am getting extra data that I do not want. In the example I provided, I am getting a 5th index/array at the end that looks like:
4 => array (
0 => 10000,
1 => 0.10
)
I don't want this last piece, since I find it redundant considering that I know that 5000 pieces cost $0.10 each, so I can assume that 10000 will cost the same price when "4000" is the highest quantity given in the original array.
So I want to ask for help in removing this last piece.
Also, I was wondering if someone had a better coding method in general for converting this array.
You could just do in your inner foreach:
foreach ($pricearray as $index => $array) {
if ($q >= $array[0]) {
if($q == 10000) { continue; }
$new_array = array($q, $array[1]);
}
}
OK I think this should do the trick. I think the problem was in your comparison... See code:
function getRelativePrices($pricearray) {
$relativeprices= array();
$types = array(10,100,500,1000,5000,10000);
foreach($pricearray as $p) {
$new_array = array();
foreach($types as $t) {
if($p[0] <= $t) {
$new_array = array($t,$p[1]);
break;
}
}
if(sizeof($new_array)) {
$relativeprices[] = $new_array;
}
}
return $relativeprices;
}
Here is an example of my test based on your code examples:
function getRelativePrices($pricearray) {
$relativeprices= array();
$types = array(10,100,500,1000,5000,10000);
foreach($pricearray as $p) {
$new_array = array();
foreach($types as $t) {
if($p[0] <= $t) {
$new_array = array($t,$p[1]);
break;
}
}
if(sizeof($new_array)) {
$relativeprices[] = $new_array;
}
}
return $relativeprices;
}
$test = array (
0 => array (
0 => 50,
1 => 0.80
),
1 => array (
0 => 300,
1 => 0.50
),
2 => array (
0 => 600,
1 => 0.30
),
3 => array (
0 => 1000,
1 => 0.20
),
4 => array (
0 => 4000,
1 => 0.10
)
);
print_r(getRelativePrices($test));
And the output was:
Array
(
[0] => Array
(
[0] => 100
[1] => 0.8
)
[1] => Array
(
[0] => 500
[1] => 0.5
)
[2] => Array
(
[0] => 1000
[1] => 0.3
)
[3] => Array
(
[0] => 1000
[1] => 0.2
)
[4] => Array
(
[0] => 5000
[1] => 0.1
)
)

php turning array into multi-dimensional array

i have a (dynamic) array, which in this example contains 4 sets of data (5 fields per set), but it could be only one set or up to 25 sets.
Array ( [lightwattage1] => 50 [lightvoltage1] => 12 [lightquantity1] => 2 [lightusage1] => 4 [lightcomment1] => [lightwattage2] => 60 [lightvoltage2] => 24 [lightquantity2] => 4 [lightusage2] => 5 [lightcomment2] => [lightwattage3] => 30 [lightvoltage3] => 240 [lightquantity3] => 4 [lightusage3] => 2 [lightcomment3] => [lightwattage4] => 25 [lightvoltage4] => 12 [lightquantity4] => 2 [lightusage4] => 6 [lightcomment4] => )
which i'd like to turn into something like
Array ( Array ( [lightwattage1] => 50 [lightvoltage1] => 12 [lightquantity1] => 2 [lightusage1] => 4 [lightcomment1] => ),
Array ( [lightwattage2] => 60 [lightvoltage2] => 24 [lightquantity2] => 4 [lightusage2] => 5 [lightcomment2] => ),
Array ( [lightwattage3] => 30 [lightvoltage3] => 240 [lightquantity3] => 4 [lightusage3] => 2 [lightcomment3] => ),
Array ( [lightwattage4] => 25 [lightvoltage4] => 12 [lightquantity4] => 2 [lightusage4] => 6 [lightcomment4] => )
)
the original array is created this way:
$light = Array();
foreach( $_POST as $key => $val )
{
//field names that start with light to go in this array
if (strpos($key, 'light') === 0) {
$light[$key] = $val;
}
}
the field name digit is already added with JS before form submission, and not by php script.
any hint much appreciated.
This is not an exacty answer to you question, but...
You can use arrays in POST variables like so:
<input name="light[1][wattage]" />
<input name="light[1][voltage]" />
<input name="light[2][wattage]" />
<input name="light[2][voltage]" />
will give you:
$_POST['light'] == array(
1 => array(
'wattage' => '...',
'voltage' => '...',
),
2 => array(
'wattage' => '...',
'voltage' => '...',
),
)
Try this:
$prefixes = array();
$postfixes = array();
foreach($original_array as $key=>$value)
{
preg_match('/^([^\d]*)(\d+)$/',$key,$matches);
if(count($matches)>1)
{
if(!in_array($matches[1], $prefixes)) $prefixes[] = $matches[1];
if(!in_array($matches[2], $postfixes)) $postfixes[] = $matches[2];
}
}
$new_array = array();
foreach($postfixes as $postfix)
{
$new_element = array();
foreach($prefixes as $prefix)
{
if(isset($original_array[$prefix.$postfix])) $new_element[$prefix.$postfix] = $original_array[$prefix.$postfix];
}
$new_array[] = $new_element;
}
given an $original_array equal to described, will produce $new_array:
Array
(
[0] => Array
(
[lightwattage1] => 50
[lightvoltage1] => 12
[lightquantity1] => 2
[lightusage1] => 4
[lightcomment1] =>
)
[1] => Array
(
[lightwattage2] => 60
[lightvoltage2] => 24
[lightquantity2] => 4
[lightusage2] => 5
[lightcomment2] =>
)
[2] => Array
(
[lightwattage3] => 30
[lightvoltage3] => 240
[lightquantity3] => 4
[lightusage3] => 2
[lightcomment3] =>
)
[3] => Array
(
[lightwattage4] => 25
[lightvoltage4] => 12
[lightquantity4] => 2
[lightusage4] => 6
[lightcomment4] =>
)
)
I was uncertain about how much you knew about the elements or their order, so this code basically takes any collection of elements that end in numbers and rearranges them in groups that have the same ending number.
Try this:
$outarr = array()
$subarr = array()
$i=0;
foreach($_POST as $key => $val)
{
//only include keys starting with light:
if (strpos("light", $key)==0)
{
//create a new subarray each time we find a key that starts with "lightwattage":
if ($i>0 && strpos("lightwattage", $key)==0)
{
$outarr[] = $subarr;
}
$subarr[$key] = $val;
$i++;
}
}
$outarr[] = $subarr;
//$outarr contains what you want here

Categories