猿问

如何在不添加新数组的情况下更改关联数组内的值

我试图只显示还包含天和月的字符串的年份,然后将datum数组内部的值更新为仅显示年份。只显示年份是没有问题的,而是代替了datum值,而是添加了一个新数组。如何防止这种情况发生?

我的PHP代码:


<?PHP

while($getwpi = $getwpicon->fetch_assoc()){

  $year = date('Y', strtotime($getwpi['datum']));

  $wpi[]['datum'] = $year;

  $wpi[] = $getwpi;

}

echo '<pre>';

print_r($wpi);

echo '</pre>';

?>

我也尝试过:


$wpi[]['datum'][] = $year;

但这仍然增加了一个新的数组。



皈依舞
浏览 127回答 1
1回答

慕森卡

请注意,这:$wpi[]['datum'] = $year;的意思是将新元素添加到具有键数据的数组中,但您只想更新当前键。更新应该已启用,$getwpi因为这是您添加到结果数组中的元素。你应该做这个:while($getwpi = $getwpicon->fetch_assoc()){&nbsp; $year = date('Y', strtotime($getwpi['datum']));&nbsp; $getwpi['datum'] = $year; // update your field&nbsp; $wpi[] = $getwpi; // add to the result array}
随时随地看视频慕课网APP
我要回答