更新在PHP多维数组 [英] Updating a Multidimensional Array in PHP
问题描述
我有一个数组,看起来像这样
$阵列=
排列
(
[0] =>排列
(
[产品] =>神奇的小工具
[超值] => 200
) [1] =>排列
(
[产品] =>超级惊人的Widget
[超值] => 400
) [2] =>排列
(
[产品] =>有前途的小工具
[超值] => 300
) [3] =>排列
(
[产品] =>精湛的Widget
[超值] => 400
)
}
我想更新数组有为部件更改为800,而不是300。
请注意,此数组的顺序是任意的,这意味着我需要根据产品名称值(不是在它的阵列中的数量)来更新值。
我是想通过数组中的号码访问,但意识到不能因为这个原因工作,我不知道如何更改基于另一个多维数组的一个元素的值。
感谢您的帮助。
的foreach($数组和放大器; $值){
如果($值['产品'] ===有前途的Widget'){
$值['值'] = 800;
打破; //停止循环,我们已经找到了项目后,
}
}
所以,你通过数组循环,找到你想要的值,然后改变它。在&安培; $值
是这样数组通过引用传递。这意味着我们可以直接从循环数组中编辑值,而不必做 $阵列[$关键] ['值']
。
I have an array that looks like this
$array =
Array
(
[0] => Array
(
[Product] => Amazing Widget
[Value] => 200
)
[1] => Array
(
[Product] => Super Amazing Widget
[Value] => 400
)
[2] => Array
(
[Product] => Promising Widget
[Value] => 300
)
[3] => Array
(
[Product] => Superb Widget
[Value] => 400
)
}
I want to update the array to change "Promising Widget" to 800 instead of 300.
Note that the order of this array is arbitrary, meaning that I need to update the Value Based on the "Product" name value (not on it's number in the array).
I was trying to access it via the number in the array but realized that wouldn't work for that reason and I'm not sure how to change the value of one element of a multidimensional array based on another.
Thanks for any help.
foreach($array as &$value){
if($value['Product'] === 'Promising Widget'){
$value['Value'] = 800;
break; // Stop the loop after we've found the item
}
}
So, you loop through the array, find value you want, then change it. The &$value
is so the array is passed by reference. Meaning we can directly edit the values in the array from the loop, without having to do $array[$key]['Value']
.
这篇关于更新在PHP多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!