我不擅长算法。这是我的麻烦。
我有一个数组:
$test_arr = array(
0 => 'a',
1 => 'b',
2 => 'c',
3 => 'd',
4 => 'e',
5 => 'f',
6 => 'g',
7 => 'h',
8 => 'i',
);
我如何使用这样的算法重新排序:
$test_arr = array(
0 => array(
'a', 'b',
),
1 => array(
'c', 'd',
),
2 => array(
'e', 'f'
),
3 => array(
'g', 'h',
),
4 => array(
'i',
),
);
提前致谢!
答案 0 :(得分:1)
PHP已经有一个内置函数来执行完全相同的任务。那是array_chunk()
试试这个:
<?php
$test_arr = array(
0 => 'a',
1 => 'b',
2 => 'c',
3 => 'd',
4 => 'e',
5 => 'f',
6 => 'g',
7 => 'h',
8 => 'i',
);
var_dump(array_chunk($test_arr, 2));
?>
答案 1 :(得分:0)
这是您正在寻找的算法:
$test_arr = array(
0 => 'a',
1 => 'b',
2 => 'c',
3 => 'd',
4 => 'e',
5 => 'f',
6 => 'g',
7 => 'h',
8 => 'i',
);
$tmp_array = [];
$new_array = [];
$i = 1;
foreach($test_arr as $k => $v){
if($i % 2 == 0){
$tmp_array[] = $v;
$new_array[] = $tmp_array;
$tmp_array = [];
}else{
$tmp_array[] = $v;
}
$i++;
}
if(count($tmp_array) > 0){
$new_array[] = $tmp_array;
}
echo '<pre>';
print_r($new_array);
答案 2 :(得分:0)
此解决方案循环遍历给定数组,并且仅当前键为0或偶数时才将当前值和下一个值保存到新数组。
<?php
$test_arr = array(
0 => 'a',
1 => 'b',
2 => 'c',
3 => 'd',
4 => 'e',
5 => 'f',
6 => 'g',
7 => 'h',
8 => 'i',
);
$newarray = array();
foreach( $test_arr as $key => $value){
if ( ($key == 0) || (($key % 2) == 0)){
if( isset($test_arr[($key + 1)]) ) { $next = $test_arr[($key + 1)]; } else { $next = ''; }
$newarray[] = array($value, $next);
}
}
echo print_r($newarray, true);
?>
<强>结果强>
Array
(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[0] => c
[1] => d
)
[2] => Array
(
[0] => e
[1] => f
)
[3] => Array
(
[0] => g
[1] => h
)
[4] => Array
(
[0] => i
[1] =>
)
)