所以我想说我有一个多维数组
$myArray = [
0 = [
fruit = 'apple',
juice = 'orange',
cars = [bmw = 'blue', audi = 'red', ford = 'yellow']
],
1 = [
fruit = 'strawberry',
juice = 'grape',
cars = [bmw = 'grey', mazda = 'blue', hummer = 'orange']
],
]
以及汽车的一些替换数组值
$replaceCarsArray = [ferrari = 'red', lamborghini = 'blue, masarati = 'pink']
我使用$ key =>来预测数组& $ values(通过引用传递的值)
foreach ($myArray as $key => &$values) {
foreach ($values as $key2 => &$value) {
if ($key2 == 'cars'){
$value = $replaceCarsArray;
}
}
}
可以使用$ replaceCarsArray
来替换整个汽车的价值但如果我想要定位该汽车数组中的一个项目并更改颜色该怎么办?所以这就是我的尝试:
foreach ($myArray as $key => &$values) {
foreach ($values as $key2 => &$value) {
if ($key2 == 'cars' && $value['bmw'] != 'red'){
$value['bmw'] = 'red';
}
}
}
然而,这似乎不起作用,并且宝马颜色不会更新为红色。我怎样才能更改这些数据?
请注意这是示例数据,我写的很快就出于所有意图和目的,我可以访问所有值,并且我的代码中没有任何语法错误,如此处所示。
答案 0 :(得分:0)
尝试以下
$myArray[$key][$key2]['bmw'] = 'blue';
答案 1 :(得分:0)
这对我有用
<?php
$myArray = [
0 => [
'fruit' => 'apple',
'juice' => 'orange',
'cars' => ['bmw' => 'blue', 'audi' => 'red', 'ford' => 'yellow']
],
1 => [
'fruit' => 'strawberry',
'juice' => 'grape',
'cars' => ['bmw' => 'grey', 'mazda' => 'blue', 'hummer' => 'orange']
]
];
echo "<pre>";
var_dump($myArray);
echo "</pre>";
foreach ($myArray as $key => &$values) {
foreach ($values as $key2 => &$value) {
if ($key2 == 'cars' && $value['bmw'] != 'red'){
$value['bmw'] = 'red';
}
}
}
echo "<pre>";
var_dump($myArray);
echo "</pre>";
echo $myArray[0]['cars']['ford'];
echo $myArray[0]['cars']['bmw'];