我正在尝试将此数组的内容分配到一个新数组中,新数组键必须总共只包含4 个计数,其中hit = 0
等于1 个计数,hit = 1
等于2 个计数。
从分配给变量的数据库中获取原始数组$ret
:
Array
(
[0] => Array (
[id] => 33, [hits] => 0
)
[1] => Array (
[id] => 32, [hits] => 0
)
[2] => Array (
[id] => 31, [hits] => 0
)
[3] => Array (
[id] => 30, [hits] => 0
)
[4] => Array (
[id] => 29, [hits] => 0
)
[5] => Array (
[id] => 28, [hits] => 1
)
[6] => Array (
[id] => 27, [hits] => 0
)
[7] => Array (
[id] => 26, [hits] => 0
)
[8] => Array (
[id] => 25, [hits] => 1
)
[9] => Array (
[id] => 24, [hits] => 0
)
[10] => Array (
[id] => 23, [hits] => 1
)
[11] => Array (
[id] => 22, [hits] => 1
)
[12] => Array (
[id] => 21, [hits] => 0
)
[13] => Array (
[id] => 20, [hits] => 1
)
[14] => Array (
[id] => 19, [hits] => 1
)
[15] => Array (
[id] => 18, [hits] => 0
)
[16] => Array (
[id] => 17, [hits] => 0
)
[17] => Array (
[id] => 16, [hits] => 0
)
[18] => Array (
[id] => 15, [hits] => 0
)
[19] => Array (
[id] => 14, [hits] => 1
)
[20] => Array (
[id] => 10, [hits] => 0
)
[21] => Array (
[id] => 9, [hits] => 1
)
[22] => Array (
[id] => 8, [hits] => 0
)
[23] => Array (
[id] => 7, [hits] => 0
)
[24] => Array (
[id] => 3, [hits] => 1
)
)
我构造了这段代码:
$new_arr = array();
$row = 0;
$ctr = 0;
foreach($ret as $ak1 => $av1) {
if($ctr == 4) {
$row++;
$ctr = 0;
}
else {
}
if($av1['hits'] == 0) {
$ctr++;
$new_arr[$row][] = $av1;
}
else {
$ctr+=2;
$new_arr[$row][] = $av1;
}
}
print_r($new_arr);
前几个键[0] [1] [2] [3]
似乎包含正确的结果,但不是从键开始[4]
Array
(
[0] => Array
(
[0] => Array (
[id] => 33
[hits] => 0
)
[1] => Array (
[id] => 32
[hits] => 0
)
[2] => Array (
[id] => 31
[hits] => 0
)
[3] => Array (
[id] => 30
[hits] => 0
)
)
[1] => Array
(
[0] => Array (
[id] => 29
[hits] => 0
)
[1] => Array (
[id] => 28
[hits] => 1
)
[2] => Array (
[id] => 27
[hits] => 0
)
)
[2] => Array
(
[0] => Array (
[id] => 26
[hits] => 0
)
[1] => Array (
[id] => 25
[hits] => 1
)
[2] => Array (
[id] => 24
[hits] => 0
)
)
[3] => Array
(
[0] => Array (
[id] => 23
[hits] => 1
)
[1] => Array (
[id] => 22
[hits] => 1
)
)
[4] => Array
(
[0] => Array (
[id] => 21
[hits] => 0
)
[1] => Array (
[id] => 20
[hits] => 1
)
[2] => Array (
[id] => 19
[hits] => 1
)
[3] => Array (
[id] => 18
[hits] => 0
)
[4] => Array (
[id] => 17
[hits] => 0
)
[5] => Array (
[id] => 16
[hits] => 0
)
[6] => Array (
[id] => 15
[hits] => 0
)
[7] => Array (
[id] => 14
[hits] => 1
)
[8] => Array (
[id] => 10
[hits] => 0
)
[9] => Array (
[id] => 9
[hits] => 1
)
[10] => Array (
[id] => 8
[hits] => 0
)
[11] => Array (
[id] => 7
[hits] => 0
)
[12] => Array (
[id] => 3
[hits] => 1
)
)
)
我感到很困惑。