duaijiao0648 2015-08-27 09:35
浏览 27
已采纳

从数组中创建内部字符串的相等部分

Lets say I have a array of 120 items. I need to separate them into comma separated texts in equal chunks.

For example if I choose to separate all elements to chunks of 50 / 120 items should be separated as 50, 50 and 20.

I tried below code:

$lines = file("all.txt", FILE_IGNORE_NEW_LINES);
$allarr[] = array_chunk($lines, 50);


foreach($allarr[0]  as $chunks);
{
    $str = implode($chunks,",");

    echo $str."<br><br>";
 }

The above code create the correct chunks of array. But When I want to loop it and add implode. It just prints the last array.

EDIT : For easy understanding below is the example

$lines = array(1,2,3,4,5);
$allarr = array_chunk($lines, 3);
var_dump($allar);

foreach($allarr as $chunks);
{

var_dump($chunks);
$str = implode($chunks,",");

}

Where $allar output is

array(2) {
  [0]=>
  array(3) {
    [0]=>
    int(1)
    [1]=>
    int(2)
    [2]=>
    int(3)
  }
  [1]=>
  array(2) {
    [0]=>
    int(4)
    [1]=>
    int(5)
  }
}

But $chunks output is only last part of array

array(2) {
  [0]=>
  int(4)
  [1]=>
  int(5)
}
  • 写回答

1条回答 默认 最新

  • du1462 2015-08-27 09:38
    关注

    You have an extra ; that's ending the foreach loop early.

    foreach ($allarr as $chunks);
                                ^
    

    So you're doing nothing in the foreach loop, and then doing var_dump($chunks) after the loop is finished. That's why it only shows the last chunk.

    Get rid of that ; and it will work correctly.

    DEMO

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 像这种代码要怎么跑起来?
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件