【问题标题】:String array element print in new line [closed]在新行中打印字符串数组元素[关闭]
【发布时间】:2017-09-06 13:55:57
【问题描述】:

这是我的代码:

<?php

function spilt($number){
    $array = array("john doe alex hales johnny johnn arnold ronnie",
                   "john doe alex hales johnny johnn arnold ronnie",
                   "john doe alex hales johnny johnn arnold ronnie");

    for ($i=0; $i <count($array) ; $i++) {
        $string =  explode(" ", $array[$i]);
        echo"<br>";
        for ($j = 0; $j < count($string); $j++) {
            echo $string[$j]." ";
            if ($j+1 == $number ) {
                echo "<br>";
            }
        }
    }
}

spilt(3);
  1. 当我将 1 传递给函数时,所有数组元素都应该像这样中断:

    john  
    doe 
    alex 
    hales 
    johnny 
    johnn 
    arnold 
    ronnie
    
  2. 当我将 2 传递给函数时,输出应该是这样的:

    john doe 
    alex hales  
    johnny johnn 
    arnold ronnie
    
  3. 当我将 3 传递给函数时,输出应该是这样的,以此类推:

    john doe alex
    hales johnny johnn
    arnold ronnie
    

有可能吗?

【问题讨论】:

  • 我不明白,你的问题是什么?您已经给出了结果和代码,但不应该发生的事情是,反之亦然。
  • 只需使用array_chunk()
  • 我的代码运行完美,我只希望当我传递值以函数所有数组元素根据我的传递值中断时,我想要我在上面写的输出。我不知道如何解决它。代码工作正常
  • 我的代码运行完美 - 那么你没有问题,或者你没有在你的 OP 中恰当地解释它。
  • 兄弟你能根据我想要的输出来帮助我吗? @Script47

标签: php arrays


【解决方案1】:

您唯一的问题是:if ($j+1 == $number )

该条件意味着您仅在 $j+1 完全等于 $number 时插入新行。您需要查看它是否可以被 $number 整除。

if (($j + 1) % $number == 0)

【讨论】:

  • 谢谢你的回答对我帮助很大。
  • 不客气。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多