Ognj3n
Ognj3n

Reputation: 759

Taking every n-th element of one array and putting it into another array 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.

Upvotes: 0

Views: 50

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92874

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

Upvotes: 4

Related Questions