Php 无效参数错误:foreach
运行以下代码时,我收到一个错误消息,即为foreach()提供的无效参数。:Php 无效参数错误:foreach,php,foreach,arguments,Php,Foreach,Arguments,运行以下代码时,我收到一个错误消息,即为foreach()提供的无效参数。: $datatoconvert = "Some Word"; $converteddata = ""; $n=1; $converteddata .=$datatoconvert[0]; foreach ($datatoconvert as $arr) { if($arr[n] != ' ') { $n++; } else { $n++; $converteddata .=$arr[n]; } }
$datatoconvert = "Some Word";
$converteddata = "";
$n=1;
$converteddata .=$datatoconvert[0];
foreach ($datatoconvert as $arr) {
if($arr[n] != ' ') {
$n++;
} else {
$n++;
$converteddata .=$arr[n];
}
}
代码应该找到每个单词的第一个字符,并返回包含这些字符的字符串。因此,在上面的示例中,我试图以“SW”的形式获得输出。您需要首先将字符串$datatoconvert分解为一个数组
$words = explode(' ', $datatoconvert);
我们应该做到这一点。然后在$words上使用foreach()。首先需要将字符串$datatoconvert分解为一个数组
$words = explode(' ', $datatoconvert);
我们应该做到这一点。然后是$words上的foreach()。必须为
foreach
提供数组或iterable
要实现您的目标,请执行以下操作:
$string = "Some Word";
$string = trim($string); //Removes extra white-spaces aroud the $string
$pieces = explode(" ", $string); //Splits the $string at the white-spaces
$output = ""; //Creates an empty output string
foreach ($pieces as $piece) {
if ($piece) //Checks if the piece is not empty
$output .= substr($piece, 0, 1); //Add the first letter to the output
}
请记住,如果您使用的是多字节字符串,请阅读PHP mbstring函数
希望我能提供帮助。您必须为
foreach
提供数组或iterable
要实现您的目标,请执行以下操作:
$string = "Some Word";
$string = trim($string); //Removes extra white-spaces aroud the $string
$pieces = explode(" ", $string); //Splits the $string at the white-spaces
$output = ""; //Creates an empty output string
foreach ($pieces as $piece) {
if ($piece) //Checks if the piece is not empty
$output .= substr($piece, 0, 1); //Add the first letter to the output
}
请记住,如果您使用的是多字节字符串,请阅读PHP mbstring函数
希望我能帮上忙。当你这么做的时候
$datatoconvert = "Some Word";
$converteddata = "";
$n=1;
$converteddata .=$datatoconvert[0];
你将得到的是
你可以通过爆炸来代替
$datatoconvert = "Some Word";
$converteddata = "";
$words = explode(" ", $datatoconvert );
foreach ($words as $a) {
$converteddata .= $a[0];
}
echo $converteddata ;
当你这样做的时候
$datatoconvert = "Some Word";
$converteddata = "";
$n=1;
$converteddata .=$datatoconvert[0];
你将得到的是
你可以通过爆炸来代替
$datatoconvert = "Some Word";
$converteddata = "";
$words = explode(" ", $datatoconvert );
foreach ($words as $a) {
$converteddata .= $a[0];
}
echo $converteddata ;