阵列替换不起作用

时间:2014-08-22 03:54:16

标签: php arrays

以下是我的数组,我需要替换'battle_health'的值

$battlepokemon= array();

$i = 1;
while($rows = mysql_fetch_assoc($res))
{
$path = mysql_query(" SELECT * FROM pokemons WHERE pk_id = '".$rows['pkmn_id']."' ");
$pokemon = array(
'opponent_increment' => $i,
'id' => $rows['pkmn_id'],
'battle_poke'=> mysql_result($path,0,"path"),
'battle_level' => $rows['level'],
'battle_health' => $rows['health']
);
$i++;
$battlepokemon[]= $pokemon;
}

替换代码是:

$i = 1;
foreach ($battlepokemon as $key => $value) 
{
if($value['opponent_increment'] == $opponent_increment)
{
$value['battle_health'] = 0;
echo "Data replaced!";
}
$i++;
}
print_r($battlepokemon);

上面的代码正在工作......从开始到结束..但代码所示的值不会被'0'替换! 我想我一定错过了什么!

2 个答案:

答案 0 :(得分:4)

您需要传输参考,而不是值。将&添加到以下句子

foreach ($battlepokemon as $key => &$value) 
                                   ^

我试过这个例子

<?php
$arr = array('12', '34');
foreach($arr as $key => &$value){
  $value = 0;
}
var_dump($arr);
?>

希望它可以帮到你

答案 1 :(得分:0)

您可以使用for Loop Because unlike foreach loop, it doesn't perform an array copy before transversal

来实现这一目标
$arr = array('12', '34');
for($i = 0, $count = count($arr); $i < $count; $i++){
    $arr[$i] = 0;
}
var_dump($arr);

或者如果您只想使用Foreach,则需要通过传递reference来避免新的数组副本:

   $arr = array('12', '34');
   foreach($arr as $key => &$value)
   {
       $value = 0;
   }
   var_dump($arr);