[英]Creating multidimensional array PHP
I'm attempting to create a multidimensional array which should have the ID and quantity from the $_POST array. 我正在尝试创建一个多维数组,该数组应具有$ _POST数组中的ID和数量。 At the moment it seems to put every quantity into each an element with each ID.However I want it to take the first elements from each array and then add them together to a new array and so on. 目前,似乎将每个数量放入每个具有每个ID的元素中,但是我希望它从每个数组中提取第一个元素,然后将它们添加到一个新数组中,依此类推。
Whereas it should be 鉴于应该
ID 1 - Quantity 100
ID 2 - Quantity 50
etc 等等
But at the moment I get this 但是现在我明白了
array(16) {
[0]=>
array(2) {
["id"]=>
string(1) "1"
["quantity"]=>
string(2) "50"
}
[1]=>
array(2) {
["id"]=>
string(1) "1"
["quantity"]=>
string(3) "100"
}
[2]=>
array(2) {
["id"]=>
string(1) "1"
["quantity"]=>
string(3) "100"
}
[3]=>
array(2) {
["id"]=>
string(1) "1"
["quantity"]=>
string(3) "100"
}
[4]=>
array(2) {
["id"]=>
string(2) "12"
["quantity"]=>
string(2) "50"
}
[5]=>
array(2) {
["id"]=>
string(2) "12"
["quantity"]=>
string(3) "100"
}
[6]=>
array(2) {
["id"]=>
string(2) "12"
["quantity"]=>
string(3) "100"
}
[7]=>
array(2) {
["id"]=>
string(2) "12"
["quantity"]=>
string(3) "100"
}
[8]=>
array(2) {
["id"]=>
string(1) "2"
["quantity"]=>
string(2) "50"
}
[9]=>
array(2) {
["id"]=>
string(1) "2"
["quantity"]=>
string(3) "100"
}
[10]=>
array(2) {
["id"]=>
string(1) "2"
["quantity"]=>
string(3) "100"
}
[11]=>
array(2) {
["id"]=>
string(1) "2"
["quantity"]=>
string(3) "100"
}
[12]=>
array(2) {
["id"]=>
string(1) "6"
["quantity"]=>
string(2) "50"
}
[13]=>
array(2) {
["id"]=>
string(1) "6"
["quantity"]=>
string(3) "100"
}
[14]=>
array(2) {
["id"]=>
string(1) "6"
["quantity"]=>
string(3) "100"
}
[15]=>
array(2) {
["id"]=>
string(1) "6"
["quantity"]=>
string(3) "100"
}
}
Here is my PHP code. 这是我的PHP代码。
foreach($_POST['sweetids'] as $id) {
foreach($_POST['quantites'] as $quantity) {
$stock_array[] = array(
"id"=> $id,
"quantity" => $quantity
);
}
} }
I think this is what you're trying to achieve: 我认为这是您要实现的目标:
foreach($_POST['sweetids'] as $key=>$id) {
$stock_array[] = array(
"id"=> $id,
"quantity" => $_POST['quantities'][$key]
);
}
You're iterating $_POST['quantities']
for every $_POST['sweetids']
which is probably not what you intend. 您正在为每个$_POST['sweetids']
迭代$_POST['quantities']
,这可能不是您想要的。 When you iterate both, your result will be every combination of sweetids
and quantities
, not each pair of them. 当您同时迭代两者时,结果将是sweetids
和quantities
每一个组合,而不是每对 。
I'm guessing you meant something more like: 我猜你的意思更像是:
// Assuming you already verified that $_POST['quantities'] and $_POST['sweetids'] exist
// and that both of them have the same number of elements
for ( $i = 0, $len = count($_POST['sweetids']); $i < $len; $i++ ) {
$stock_array[] = array(
'id' => $_POST['sweetids'][$i],
'quantity' => $_POST['quantities'][$i]
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.