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

时间:2016-04-07 12:47:27

标签: php arrays

所以我有array这样:

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" }

根据另一个名为$anotherArray的数组中的元素数量,让我们说$anotherArray有3个元素,我应该先取第一个数组的3个元素,如果有第二个3个元素依此类推,并将它们放入另一个数组中。我试过这样:

$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);
    }
    }

所以我希望这个$restructured数组看起来像这样:

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

相反,当我var_dump($restructured)时,它看起来像这样:

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" }

请帮忙,我坚持这个。

1 个答案:

答案 0 :(得分:4)

使用array_chunkarray_map函数实现此目标要简单得多:

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

print_r($restructured);

输出:

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

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