简体   繁体   English

从数组中获取一组值

[英]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, 我想做的是从每个$nums数组中获取一组$ data数组,

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

Another alternative is to use another flavor array_splice , it basically takes the array based on the offset that you inputted. 另一种选择是使用另一个风味array_splice ,它基本上根据您输入的偏移量获取数组。 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: 但是,您需要另一个循环,只需保存/记录最后一个索引,以便知道从哪里开始下一个num提取:

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

You can array_shift to remove the first element. 您可以array_shift删除第一个元素。

$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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM