我的问题是,我有一个2D Array
,我想override
设置的元素的值。
我的代码如下:
$indes="-1";
$inupccode="-1";
$inuomcode="-1";
$instdpack="-1";
$inweight="-1";
$inlength="-1";
$inwidth="-1";
$inheight="-1";
$inunitprice="-1";
$infamcode="-1";
$basicInfo = array(array($indes,"prdes1_35", $inupccode,
"prupc#_2", $inuomcode,"prwuts_3-1",
$instdpack,"prwuns_12", $inweight,
"prgrwt_11", $inlength,"prlong_7",
$inwidth,"prwide_7", $inheight,"prhigh_7",
$inunitprice,"prprce_12", $infamcode,"proga2"));
echo "before";
print_r($basicInfo);
foreach($basicInfo as $value){
foreach ($value as $id){
if($id == "prdes1_35"){
$value = 2;
}
}
}
echo "after";
print_r($basicInfo);
在 $indes
值的代码中,我想从 -1 to 2
更改,并且提醒数组值必须保持为" -1
"。我怎样才能做到这一点?
首先最大的问题:我不认为你的代码能达到你想要实现的目标。您确定您了解(多维)数组吗?
另一个问题是你尝试改变$value
的方式。请查看此帖子:
(https://stackoverflow.com/questions/15024616/php-foreach-change-original-array-values)
以获取有关如何更改使用 Foreach 运行的数组的信息。
最简单的解决方案是:
foreach($basicInfo as &$value){
foreach ($value as $id){
if($id == "prdes1_35"){
$value = 2;
}
}
}
注意$value变量前面的与号 (&)。引用的帖子和链接包含理解其含义所需的所有解释。
从性能上讲,这将是最好的解决方案,尤其是当您的阵列变大时:
foreach($basicInfo as $key => $value){
foreach ($value as $id){
if($id == "prdes1_35"){
$basicInfo[$key][$value] = 2;
}
}
}
注意:我没有更改您的代码逻辑(我认为这已损坏)。我刚刚演示了在使用 foreach 迭代数组时如何更改值。