douzai2562 2016-04-07 12:47
浏览 202
已采纳

获取一个数组的每个第n个元素并将其放入另一个数组PHP中

So I have an array like this:

array(6) { [0]=> string(11) "12323423423" [1]=> string(4) "tito" [2]=> string(6) "235345" [3]=> string(14) " 564534534534" [4]=> string(5) "kralj" [5]=> string(6) "435345" }

Depending on number of elements from another array called $anotherArray, let's say $anotherArray has 3 elements, I should take first 3 elements of first array, then if there are second 3 elements and so on, and put them into another array. I tried it like so:

$lengthManuelni=count($string);// $string being array displayed uphere
$lengthAnothera=count($anotherArray);
for ($i = 0; $i < $lengthManuelni; $i += $lengthAnothera) { 
    for ($j = 0; $j < $lengthAnothera; $j++) {
        $restructured [$j] = $string[$i + $j];
        var_dump($restructured);
    }
    }

So i would like this $restructured array to look like this:

array(2) { [0]=> string(23) "12323423423,tito,235345" [1]=> string(28) " 564534534534,kralj,435345" }

Instead it when I do var_dump($restructured) it looks like this:

array(1) { [0]=> string(11) "12323423423" } array(2) { [0]=> string(11) "12323423423" [1]=> string(4) "tito" } array(3) { [0]=> string(11) "12323423423" [1]=> string(4) "tito" [2]=> string(6) "235345" } array(3) { [0]=> string(14) " 564534534534" [1]=> string(4) "tito" [2]=> string(6) "235345" } array(3) { [0]=> string(14) " 564534534534" [1]=> string(5) "kralj" [2]=> string(6) "235345" } array(3) { [0]=> string(14) " 564534534534" [1]=> string(5) "kralj" [2]=> string(6) "435345" }

Please help, I'm stuck with this.

  • 写回答

1条回答 默认 最新

  • doujiao6116 2016-04-07 13:01
    关注

    It's much simpler to achieve this using array_chunk and array_map functions:

    $restructured = array_map(function($v){
        return implode(",", $v);
    }, array_chunk($lengthManuelni, 3));
    
    print_r($restructured);
    

    The output:

    Array
    (
        [0] => 12323423423,tito,235345
        [1] => 564534534534,kralj,435345
    )
    

    http://php.net/manual/en/function.array-chunk.php

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

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配