[英]PHP foreach change two-dimensional original array values
我需要將空值替換為 0 並將原始數組更改為輸出。 我的代碼不起作用...只更改第二個 foreach 循環值。 怎么做? 我需要的輸出數組是...(我的空值不是固定在鍵中)非常感謝...我的數組:
Array
(
[0] => Array
(
[D1] => 2
[D2] => 2
[D3] => (Expect the null value to change to 0)
[D4] => (Expect the null value to change to 0)
[D6] => (Expect the null value to change to 0)
[N1] => 1
[N2] => 1
[N3] => (Expect the null value to change to 0)
[N4] => (Expect the null value to change to 0)
[N5] => (Expect the null value to change to 0)
)
[1] => Array
(
[D1] => 3
[D2] => 2
[D3] => 2
[D4] => 2
[D5] => (Expect the null value to change to 0)
[D6] => (Expect the null value to change to 0)
[T1] => 1
[T2] => 1
[T3] => -1
[T4] => (Expect the null value to change to 0)
[T5] => (Expect the null value to change to 0)
)
)
下面是我的代碼:
foreach($myArray as $key=> $value){
foreach($value as $key2 => $value2){
if(empty($value[$key2])){
$value[$key2]="0";
}
//print_R($value[$key2]);
}
foreach($myArray as $key=> $value){
foreach($value as $key2 => $value2){
if(empty($value[$key2]) || $value[$key] === null){ //added null checking, you can add more: $value[$key] == ""
$value[$key2] = 0; //changed to int (using "0" makes string)
}
//print_R($value[$key2]);
}
您可以使用&
在 foreach 循環中傳遞變量引用。 你可以試試下面的代碼。
foreach ($myArray as $key => &$value) {
foreach ($value as $key2 => $value2) {
if($value2 == null) {
$value[$key2]="0";
}
}
}
print_r($myArray);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.