带有if语句的for循环-不带逗号的数组


for loop with if statement - array without comma

这是我的代码部分:

for( $i = $aKeys['iStart']; $i < $aKeys['iEnd']; $i++ )
{
        $aData = $this->aProducts[$aProducts[$i]];
        $content .= '"'.$aData['sName'].'"';
        if ($i < $aKeys['iEnd'])  
        {
           $content .= ', '; 
        } 
        $i2++;
} 

完整的代码给了我这样的结果:

["word1", "word2", "word3", ] 

这是一个简单的数组,我会使用它,但这不起作用,因为在word3之后有一个逗号符号。如何编写这个if语句来获得类似:["word1", "word2", "word3"]的结果?

对长度-1设置一个条件来修复您的错误。

for( $i = $aKeys['iStart']; $i < $aKeys['iEnd']; $i++ ){
        $aData = $this->aProducts[$aProducts[$i]];
        $content .= '"'.$aData['sName'].'"';
        if ($i < $aKeys['iEnd']-1) {
        $content .= ', '; 
        } 
        $i2++;
      } 

或者,您也可以使用array。并在最后简单地implode他们。

for( $i = $aKeys['iStart']; $i < $aKeys['iEnd']; $i++ ){
    $aData = $this->aProducts[$aProducts[$i]];
    $content[] = '"'.$aData['sName'].'"';
}
$content = '"' . implode('","', $content) . '"';

您可以使用rtrim()删除逗号。

rtrim($content, ',');

正如我所看到的,你希望所有的名字都用逗号分隔。你也可以这样做:

$content = array();
for( $i = $aKeys['iStart']; $i < $aKeys['iEnd']; $i++ ){
    $aData = $this->aProducts[$aProducts[$i]];
    $content[] = $aData['sName'];
}
echo implode(',',$content);
for( $i = $aKeys['iStart']; $i < $aKeys['iEnd']; $i++ ){
        $aData = $this->aProducts[$aProducts[$i]];
        $content .= '"'.$aData['sName'].'"';
        if ($i < $aKeys['iEnd'] && $i!=($aKeys['iEnd']-1)) { //this condition also considers $i not to be the last element of the array before appending the comma to it.
        $content .= ', '; 
        } 
        $i2++;
      } 

使用array_push();函数

$var = array();
loop(condition){
    array_push($var, $value);
}