Can't change a value inside a php list
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.
This is my code...
while ($i<sizeof($my_array)){
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?
Use foreach
with reference:
$i = 0;
foreach ( $my_array as $key => &$val ) {
++$i;
if ($key == "fruit"){
$val = "ananas" . $i;
echo $val;
}
}
$val is a copy of the data contained in $my_array[$i], not the actual data. To change the data in the array:
while ($i<sizeof($my_array)){
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
each()
doesn't pass the data as references, without modifying the loop that much:
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.
精彩评论