2013-06-14 4 views
0

내가 다음 코드를 실행하는 경우) (foreach 문에 대한 공급 잘못된 인수와 같은 오류 messge 점점 오전 : 코드는 모든 단어의 첫 번째 문자를 찾을 문자열을 반환해야합니다잘못된 인수 오류 : foreach는

$datatoconvert = "Some Word"; 
$converteddata = ""; 
$n=1; 

$converteddata .=$datatoconvert[0]; 

foreach ($datatoconvert as $arr) { 
if($arr[n] != ' ') { 
    $n++; 
} else { 
    $n++; 
    $converteddata .=$arr[n]; 
} 
} 

을 이 문자들. 그래서 위의 예에서 출력을 "SW"로 얻으려고합니다.

답변

1

$ datatoconvert 문자열을 먼저 배열로 분해해야합니다.

$words = explode(' ', $datatoconvert); 

트릭을해야합니다. 다음 $ 단어에 foreach().

1

foreach에 대한 배열 또는 반복 가능 문자를 제공해야합니다. 당신이 멀티 바이트 문자열을 사용하는 경우,

$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 기능에 대해 읽어 :

당신이 뭘 하려는지 달성하기 위해.

희망이 있습니다.

1

당신이 할 때

$datatoconvert = "Some Word"; 
$converteddata = ""; 
$n=1; 

$converteddata .=$datatoconvert[0]; 

당신은 쉽게 얻을 수 있습니다 (Live output)

string(1) "S" 

대신

$datatoconvert = "Some Word"; 
$converteddata = ""; 

$words = explode(" ", $datatoconvert); 
foreach ($words as $a) { 
    $converteddata .= $a[0]; 
} 
echo $converteddata ; 

Live output

+1

+1 아니라 폭발되어 볼 수있는 콘텐츠 설명하다 디. –