我一直在寻找StackOverflow上的答案,应用不同的建议,但没有解决我的问题。
我正在尝试编写一个接收数组的函数,并将数组中的每个字符串缩短为3个字符。这是我写的代码:
$days_of_week = array("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday");
function stringParse(array $string) {
for($i = 0; $i < count($string); $i++) {
$string = str_replace($string[$i], substr($string[$i],0,3), $string);
echo $string[$i].'<br />';
}
return $string;
}
stringParse($days_of_week);
foreach($days_of_week as $stry) {echo $stry.'<br />';}
我也试过更换:
$string = str_replace($string[$i], substr($string[$i],0,3), $string);
使用:
$string[$i] = substr($string[$i],0,3);
但那也不起作用。
我得到的输出是:
mon
tue
wed
thu
fri
sat
sun
monday
tuesday
wednesday
thursday
friday
saturday
sunday
在调用函数后,显然没有更改String值。关于我做错了什么的建议?
答案 0 :(得分:1)
尝试:
$days_of_week = array("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday");
$short_days_of_week = array_map(function($value) { return substr($value, 0, 3); }, $days_of_week);
var_dump($short_days_of_week);
答案 1 :(得分:0)
$days_of_week = stringParse($days_of_week);
您需要将返回值分配给变量: - )
本规范适用于我:
<?php
$days_of_week = array("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday");
function stringParse(array $string) {
for($i = 0; $i < count($string); $i++) {
$string = str_replace($string[$i], substr($string[$i],0,3), $string);
echo $string[$i].'<br />';
}
return $string;
}
$days_of_week = stringParse($days_of_week);
foreach($days_of_week as $stry) {echo $stry.'<br />';}
答案 2 :(得分:0)
您创建的函数返回一个数组,您必须将其分配给变量。
$newarray = stringParse($days_of_week);
foreach($newarray as $stry) {echo $stry.'<br />';}