2011-07-05 131 views
1
// 40 characters string combine by 5 different fields 
$field1 = apple; 
$field2 = orange; 
$field3 = pineapple; 
$field4 = banana; 
$field5 = strawberry; 

// fields will be separated with a comma 
$string = implode(", ", array_filter(array($field1, $field2, $field3, $field4, $field5))); 

// string will be cut off at about 15th characters then make a break line   
$stringList = explode("\n", wordwrap($string , 15)); 

// 1st rowField takes the 1st line of string 
$rowField1 = array_shift($nutritionalList); 
$string = implode(" ",$stringList); 
$stringList = explode("\n", wordwrap($string , 25)); 
$rowField2 = "From 1st Row continued" . "\n" . implode("\n", $stringList) . "\n \n";} 

,此輸出將顯示:如果PHP語句不工作?

$rowField1 = "apple, orange" 
$rowField2 = "From 1st Row continued \n pineapple, banana, strawberry" 

不過,我的問題是,如果$field3$field4,並且$field5是NULL,我不希望顯示$rowField2包括文字「從第一行繼續」

我試過的if/else和ISSET過程:

if (isset($stringList)) { 
    $rowField2 = "From 1st Row continued\n" . implode("\n", $stringList) . "\n\n"; 
} 
else { 
    $rowField2 = NULL; 
} 

$rowField2仍顯示「從第一行繼續」。我希望它不顯示,如果最後3個字段是NULL。

+0

是不是故意的,你寫例如'$ field1 = apple;'而不是'$ field1 =「apple」;'?我沒有看到那些定義的常量。 –

+0

@Tomalak Geret'kal:抱歉,錯字。我儘可能快地重新輸入代碼,以快速解決問題。反正,shashank的解決方案爲我工作。所以我很高興:)感謝您的查看 –

+0

您可以點擊上面的「編輯」來修復您的問題中的代碼。 –

回答

3

試試這個會輸出「apple,orange」。

這是好嗎?

<?php 
$field1 = 'apple'; 

$field2 = 'orange'; 

$field3 = ''; 

$field4 = ''; 

$field5 = ''; 

// fields will be seperated with a comma 

$string = implode(", ", array_filter(array($field1, $field2, $field3, $field4, $field5))); 

// string will be cut off at about 15th characters then make a break line 

$stringList = explode("\n", wordwrap($string , 15)); 

// 1st rowField takes the 1st line of string 

$rowField1 = array_shift($stringList); 

$string = implode(" ",$stringList); 

$stringList = explode("\n", wordwrap($string , 25)); 

$rowField2 = (isset($stringList[0]) && !empty($stringList[0])) ? "From 1st Row continued" . "\n" . implode("\n", $stringList) . "\n \n" : ''; 
echo $rowField1; 
echo "<br />"; 
echo $rowField2; 
exit; 
?> 
+0

它工作!!!!!哇。謝謝Shashank Patel! –

+0

-1:['empty'](http://php.net/manual/en/function.empty.php)不會做你認爲它的工作。 –

+0

其實我會收回-1,因爲我現在注意到他正在處理一個數組......但我仍然不會推薦'empty'。 –

1

我會用條件:

if(isset($stringList) && count($stringList) > 0){ 
    // blah blah 
} 
0

$stringList將永遠是設置,但它不會總是有它的內容。

不要使用empty,因爲它不清楚它從事什麼工作—一件事,empty("0")TRUE! —,儘管在這種情況下,在一個數組上,它會工作。

我推薦的方法:

if (count($stringList)) { 
    $rowField2 = "From 1st Row continued\n" . implode("\n", $stringList) . "\n\n"; 
} 
else { 
    $rowField2 = NULL; 
} 
+0

我也會嘗試這段代碼。謝謝! –