简体   繁体   English

php数组算法有问题

[英]Having some trouble with php array algorithm

I'm not good at algorithm.我不擅长算法。 Here is my trouble.这是我的麻烦。

I have an array:我有一个数组:

$test_arr = array(
  0 => 'a',
  1 => 'b',
  2 => 'c',
  3 => 'd',
  4 => 'e',
  5 => 'f',
  6 => 'g',
  7 => 'h',
  8 => 'i',
);

How do i reorder it with some algorithms like this:我如何使用这样的一些算法重新排序它:

$test_arr = array(
  0 => array(
    'a', 'b',
  ),
  1 => array(
    'c', 'd',
  ),
  2 => array(
    'e', 'f'
  ),
  3 => array(
    'g', 'h',
  ),
  4 => array(
    'i',
  ),
);

Thanks in advance!提前致谢!

PHP already has a builtin function to do exactly the same task. PHP 已经有一个内置函数来完成同样的任务。 That is array_chunk()那是array_chunk()

Try this:尝试这个:

<?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));
?>

Here is algorithm you are looking for:这是您正在寻找的算法:

$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);

This solution loops through the given array and saves current and next values to a new array ONLY if the current key is either 0 or an even number.此解决方案循环遍历给定的数组,仅当当前键为 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);
?>

Result结果

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] => 
        )

)

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

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