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 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?