[英]php update values of an array based on other array with the same key
I have the following scenario: 我有以下情况:
$starterArray = array ('192.168.3.41:8013'=>0,'192.168.3.41:8023'=>0,'192.168.3.41:8033'=>0);
In the requirement I have another array which counts some events of the application, this array uses the same keys as my first array, but values can change), so at the end I could have something like: 根据要求,我还有另一个数组可以计算应用程序的某些事件,该数组使用与我的第一个数组相同的键,但是值可以更改),所以最后我可以得到类似以下内容的东西:
$processArray = array ('192.168.3.41:8013'=>3,'192.168.3.41:8023'=>5,'192.168.3.41:8033'=>7);
I want to update the values of my starter array with the values of the process array, for instance, at the end, I should have: 我想用流程数组的值更新我的入门数组的值,例如,最后,我应该有:
$starterArray = array ('192.168.3.41:8013'=>3,'192.168.3.41:8023'=>5,'192.168.3.41:8033'=>7);
I know this can be achieved by using $starterArray = $processArray;
我知道可以通过使用
$starterArray = $processArray;
来实现$starterArray = $processArray;
Then in some moments, I would need to sum some units to the values of my array, for example +1 or +2: 然后,在某些时候,我需要将一些单位加到数组的值上,例如+1或+2:
It should be something like the following? 应该是以下内容吗?
foreach ($starterArray as $key => $value) {
$starterArray[$value] = $starterArray[$value]+1;
}
Then, for my process array, I need to set the values to 0 然后,对于我的过程数组,我需要将值设置为0
foreach ($processArray as $key => $value) {
$processArray[$value] = 0;
}
This is what I tried but it is not working, if somebody could help me I will really appreaciate it. 这是我尝试过的方法,但是没有用,如果有人可以帮助我,我将不胜感激。 Thanks in advance.
提前致谢。
PD: I know these are strange requirements, but that's what I am asked to do... PD:我知道这些是奇怪的要求,但这就是我要做的...
You need to put $key
in brackets, not $value
. 您需要将
$key
放在方括号中,而不是$value
。
Or, you can do: 或者,您可以执行以下操作:
foreach ($starterArray as $key => &$value) {
$value++; /* put here whatever formula you want */
}
foreach ($starterArray as $key => $value) {
$starterArray[$key] = $value+1;
// or $starterArray[$key] = 0;
}
You are almost there:- 您几乎在那里:-
foreach ($processArray as $key => $value) {
$starterArray[$key] = $value +1;
}
and then:- 接着:-
foreach ($processArray as $key => $value) {
$processArray[$key] = 0;
}
However, you could do this all in one loop:- 但是,您可以在一个循环中完成所有操作:
foreach ($processArray as $key => $value) {
$starterArray[$key] = $value +1;
$processArray[$key] = 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.