2011-07-05 86 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

我也会尝试这段代码。谢谢! –