I have the following php loop that takes an array that contains a set of arrays. I use this code to convert each array to a list, so I can manipulate the elements better.
我有以下php循環,它接受一個包含一組數組的數組。我使用此代碼將每個數組轉換為列表,因此我可以更好地操作元素。
This is my code...
這是我的代碼......
while ($i
while(list($key,$val) = each($my_array[$i])){
$j = $i+1;
if ($key == "fruit"){
$val = "ananas".$j;
echo $val;
}
}
$i++;
}
When I print the "search" array (print_r($my_array)), the values don't change. I don't understand why this doesn't work as I had expected. Is there a solution to modify the $val without changing the loop structure and logic?
當我打印“搜索”數組(print_r($ my_array))時,值不會更改。我不明白為什么這不像我預期的那樣有效。有沒有一個解決方案來修改$ val而不改變循環結構和邏輯?
3 个解决方案
#1
3
Use foreach with reference:
使用foreach參考:
$i = 0;
foreach ( $my_array as $key => &$val ) {
++$i;
if ($key == "fruit"){
$val = "ananas" . $i;
echo $val;
}
}
#2
1
$val is a copy of the data contained in $my_array[$i], not the actual data. To change the data in the array:
$ val是$ my_array [$ i]中包含的數據的副本,而不是實際數據。要更改數組中的數據:
while ($i
while(list($key,$val) = each($my_array[$i])){
$j = $i+1;
if ($key == "fruit"){
$my_array[$i][$key] = "ananas";
echo $my_array[$i][$key];
}
}
$i++;
}
And it's probably easier to use a foreach loop
並且使用foreach循環可能更容易
#3
0
each() doesn't pass the data as references, without modifying the loop that much:
each()不會將數據作為引用傳遞,而不會修改循環:
if ($key == "fruit"){
$val = "ananas";
echo $val;
$my_array[$i][$key] = $val;
}
Of course, there are better ways to do that. But you wanted an answer that didn't change the loop structure.
當然,有更好的方法可以做到這一點。但是你想要一個沒有改變循環結構的答案。