php如何给数组替换元素,php – 如何正确替换数组中的value元素?

我想比较数组中的键值,如果找到匹配项来增加元素的值.

为此,我使用代码:

// 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值