Reputation: 4885
Any idea what is going on here, the array should look like so:
Array (
[69] => Array (
[KR] => 1
)
[70] => Array (
[KR] => 2
)
[70] => Array (
[LR] => 1
)
[71] => Array (
[LR] => 1
)
)
Here is my code:
foreach ($_POST as $key => $value) {
//Split the ID and Product into individual variable
$tmp = explode("_",$key);
$id = $tmp[0]; $product = $tmp[1];
//Generate array's for each sale
$sales[$id] = array($product => $value);
}
print_r($sales);
Here is the result it produces:
Array (
[69] => Array (
[KR] => 1
)
[70] => Array (
[LR] => 1
)
[71] => Array (
[LR] => 1
)
)
Here is a quick table so you can see the actual collection of variables
69_KR 1
70_KR 2
70_LR 1
71_LR 1
Upvotes: 0
Views: 54
Reputation: 224
with
$sales[$id] = array($product => $value);
you are clobbering previous versions of $sales[$id]. you are losing data.
you need another data structure to store the values returned. like a list. which would look like
sales = list of each sale. then to access the each sale iterate of the length of the list.
Upvotes: 1
Reputation: 1615
If the same sales id can occur multiple times then you shouldn't use it as an array key. The second time you have a sales id of 70, it overwrites the values of the first one.
There are many ways you can change this, here is one suggestion:
Before the foreach loop, create the empty array $sales = array();
(you're probably already doing this)
If you don't mind an associative array (IMO they make code more readable/maintainable - think about someone else altering your code in 5 years and doing a var_dump on the $sales array), then try this instead inside the foreach:
$sales[] = array("sales_id" => $id, "product" => $product, "value" => $value);
You'll have to process the array slightly differently later, but a print_r or var_dump will be very easy to read indeed. (I also like to wrap print_r's in a <pre>
tag for really nice array formatting when outputting to the browser.)
Upvotes: 1
Reputation: 357
Replace
$sales[$id] = array($product => $value);
with
$sales[$id][$product] = $value;
Upvotes: 1