Php Foreach合并到数组
我在列表中有以下数组:Php Foreach合并到数组,php,arrays,multidimensional-array,foreach,Php,Arrays,Multidimensional Array,Foreach,我在列表中有以下数组: Array ( [products] => Array ( [0] => 5 [1] => 4 [2] => 6 [3] => 8 [4] => 4 ) [qtys] => Array ( [0] => 20
Array
(
[products] => Array
(
[0] => 5
[1] => 4
[2] => 6
[3] => 8
[4] => 4
)
[qtys] => Array
(
[0] => 20
[1] => 22
[2] => 100
[3] => 0
[4] => 0
)
)
I何时组合这些阵列以实现以下目标:
Array
(
[0] => Array
(
[product_id] => 5
[qty] => 20
)
[1] => Array
(
[product_id] => 20
[qty] => 22
) ...
但有了这个原因:
$products = $post['products'];
$qtys = $post['qtys'];
$array = [];
foreach($products as $product){
foreach($qtys as $quantity){
if(!in_array($product, $array)){
$array[] = array(
'product_id' => $product,
'qty' => $quantity
);
}
}
}
echo "<pre>".print_r($array, true)."</pre>";
我尝试了很多,比如用break,continue。
我甚至尝试了array_combine,结果并不是我所期望的。
我曾考虑过使用array_unique,但没有使用多维数组(这是我所理解的)。因为您的键是数字键,并且从0开始是连续的:
foreach($post['products'] as $key => $value){
$array[] = array('product_id' => $value,
'qty' => $post['qtys'][$key]
);
}
/$post是包含所有数据的数组
$newArray=[];
对于($i=0;$i$post['products'][$i];
“数量”=>$post['qtys'][$i];
];
}
此外,我假设“products”和“qtys”数组的长度相同。您可以保留原始的
$post
数组,并使用一个简单的foreach
键:
foreach($post['products'] as $key => $value){
$array[$value] = array('product_id' => $value,
'qty' => $post['qtys'][$key]
);
}
如果您想避免重复产品,就像您的中显示的那样!在数组中,只需按产品id键输入结果即可:
function mergeProductQuantities($products, $quantities) {
//Creating an empty output array
$output = array();
//Getting the number of iterations
$limit = ($pc = count($products)) > ($qc = count($quantities)) ? $pc : $qc;
//Doing the actual iteration
for ($index = 0; $index < $limit; $index++) {
//Creating a new item
$newItem = array();
//Setting applicable values
if (isset($products[$index])) $newItem["product_id"] = $products[$index];
if (isset($quantities[$index])) $newItem["qty"] = $quantities[$index];
//Adding the new item to the output
$output[]=$newItem;
}
return $output;
}
如果需要,您可以使用$array=array\u值($array)重新编制索引
问题在于您使用的是两个嵌套循环,因此第一个数组中的所有项都将与第二个数组中的所有项配对。相反,您需要按索引循环并添加项
$result = mergeProductQuantities($post['products'], $post['qtys']);
是的,我想我需要避免重复,但最后我不必。因此,第一个解决方案是正确的。谢谢
function mergeProductQuantities($products, $quantities) {
//Creating an empty output array
$output = array();
//Getting the number of iterations
$limit = ($pc = count($products)) > ($qc = count($quantities)) ? $pc : $qc;
//Doing the actual iteration
for ($index = 0; $index < $limit; $index++) {
//Creating a new item
$newItem = array();
//Setting applicable values
if (isset($products[$index])) $newItem["product_id"] = $products[$index];
if (isset($quantities[$index])) $newItem["qty"] = $quantities[$index];
//Adding the new item to the output
$output[]=$newItem;
}
return $output;
}
$result = mergeProductQuantities($post['products'], $post['qtys']);