nikko
nikko

Reputation: 119

get a set of values from an array

i have a set of arrays:

$nums = array(2,3,1); 
$data = array(11,22,33,44,55,66);

what i want to do is to get a set of $data array from each number of $nums array,

the output must be:

output:
2=11,22
3=33,44,55
1=66 

what i tried so far is to slice the array and remove the sliced values from an array but i didn't get the correct output.

for ($i=0; $i < count($nums); $i++) { 
    $a = array_slice($data,0,$nums[$i]);
    for ($x=0; $x < $nums[$i]; $x++) { 
        unset($data[0]);
    }
}

Upvotes: 1

Views: 95

Answers (3)

Kevin
Kevin

Reputation: 41873

Another alternative is to use another flavor array_splice, it basically takes the array based on the offset that you inputted. It already takes care of the unsetting part since it already removes the portion that you selected.

$out = array();
foreach ($nums as $n) {
    $remove = array_splice($data, 0, $n);
    $out[] = $remove;
    echo $n . '=' . implode(',', $remove), "\n";
}
// since nums has 2, 3, 1, what it does is, each iteration, take 2, take 3, take 1

Sample Output

Also you could do an alternative and have no function usage at all. You'd need another loop though, just save / record the last index so that you know where to start the next num extraction:

$last = 0; // recorder
$cnt = count($data);
for ($i = 0; $i < count($nums); $i++) {
    $n = $nums[$i];
    echo $n . '=';
    for ($h = 0; $h < $n; $h++) {
        echo $data[$last] . ', ';
        $last++;
    }
    echo "\n";
}

Upvotes: 3

Viraj Amarasinghe
Viraj Amarasinghe

Reputation: 941

This is the easiest and the simplest way,

<?php

$nums = array(2,3,1); 
$data = array(11,22,33,44,55,66);
$startingPoint = 0;
echo "output:"."\n";
foreach($nums as $num){
  $sliced_array = array_slice($data, $startingPoint, $num);
  $startingPoint = $num;
  echo $num."=".implode(",", $sliced_array)."\n";
}
?>

Upvotes: 1

Eddie
Eddie

Reputation: 26844

You can array_shift to remove the first element.

$nums = array(2,3,1); 
$data = array(11,22,33,44,55,66);

foreach( $nums as $num ){
    $t = array();
    for ( $x = $num; $x>0; $x-- ) $t[] = array_shift($data);

    echo $num . " = " . implode(",",$t) . "<br />";
}

This will result to:

2 = 11,22
3 = 33,44,55
1 = 66

Upvotes: 2

Related Questions