我被卡住了)
有两个数组,$a
和$b
。我想从$b
取值并对其进行“排序”以接收$final
数组,如下所示:
array:6 [
0 => [1 => 1]
1 => [1 => 3]
2 => [1 => 5]
3 => [2 => 7]
4 => [3 => 9]
5 => [3 => 11]
]
但是我得到了这个错误的数组:
array:6 [
0 => [1 => 1]
1 => [1 => 3]
2 => [1 => 5]
3 => [2 => 1]
4 => [3 => 1]
5 => [3 => 3]
]
代码:
$final = [];
$c = 0;
$a = [3,1,2];
$b = [1,3,5,7,9,11];
foreach($a as $k => $v){
$c++;
foreach($b as $key => $val){
if($v > $key)
$final[] = [$c => $val];
}
}
dump($final);
如何判断foreach($ b)内的语句是否还要 来验证$ key应该大于其先前的值?因为我看到第3个索引处的错误数组占用了$b
( .. 3 => [2 => 1] .. )
尝试了不同的方法,但没有成功。
答案 0 :(得分:1)
如果可以修改数组a,则更方便:
$i=0; // Index of array a
foreach($b as $v){
// while a[$i] is not zero
if(! $a[$i]) {
// Go next item of array a
$i++;
}
// Put to final array
$final[] = [$i+1 => $v];
// Decrease counter
$a[$i]--;
}
print_r($final);