我想比较数组中的键值,如果找到匹配项来增加元素的值.
为此,我使用代码:
// var_dump $all_array
array(2) {
[0]=> array(6) {
[0]=> string(8) "art_7880"
[1]=> string(11) "Арт.7880"
[2]=> string(1) "1"
[3]=> NULL
[4]=> string(45) "png"
[5]=> int(1372269755)
}
[1]=> array(6) {
[0]=> string(8) "art_7880"
[1]=> string(11) "Арт.7880"
[2]=> string(1) "1"
[3]=> NULL
[4]=> string(45) "png"
[5]=> int(1372269874)
}
}
// var_dump $count
array(2) { [0]=> string(2) "10" [1]=> string(1) "1" }
// var_dump $product
array(2) { [0]=> string(10) "1372269755" [1]=> string(10) "1372269874" }
$count=$_POST['count'];
$product=$_POST['product'];
$count_arr_products=count($product);
for ($i=0; $i<=$count_arr_products; $i++){
foreach ($all_array as $keys => $elms) {
if ($product[$i]==$elms[5]) {
if($count[$i] > 0) {
$elms[2] = $count[$i];
} else {
unset($keys);
}
}
}
}
但是步骤$elms [2] = $count [$i];不工作 – 在结果值$elms [2]不改变…
解决方法:
你需要将$elms作为参考.默认情况下,它将是子数组的副本,因此赋值不会更新原始数组.
$all_array = array(array("art_7880", "Арт.7880", "1", NULL, "png", 1372269755),
array("art_7880", "Арт.7880", "1", NULL, "png", 1372269874));
$count = array("10", "1");
$product = array("1372269755", "1372269874");
$count = array("10", "1");
$product = array("1372269755", "1372269874");
$count_arr_products = count($product);
for($i=0; $i
foreach ($all_array as $keys => &$elms) { // Use a reference so we can update it
if ($product[$i]==$elms[5]){
if ($count[$i] > 0) {
$elms[2] = $count[$i];
} else {
unset($all_array[$keys]); // not unset($keys)
}
}
}
}
var_dump($all_array);
输出:
array(2) {
[0]=>
array(6) {
[0]=>
string(8) "art_7880"
[1]=>
string(11) "Арт.7880"
[2]=>
string(2) "10"
[3]=>
NULL
[4]=>
string(3) "png"
[5]=>
int(1372269755)
}
[1]=>
&array(6) {
[0]=>
string(8) "art_7880"
[1]=>
string(11) "Арт.7880"
[2]=>
string(1) "1"
[3]=>
NULL
[4]=>
string(3) "png"
[5]=>
int(1372269874)
}
}
标签:php,arrays
来源: https://codeday.me/bug/20191007/1864530.html