按步骤(数字)循环遍历数组重新排序PHP数组

时间:2014-05-23 13:25:44

标签: php arrays sorting

我有这样的数组。

注意:在我的情况下,字符串实际上是对象,但为了示例,我用简单的字符串替换它们。

$array = (
    0 => "pear basket 1", 
    1 => "apple basket 1", 
    2 => "orange basket 1",
    3 => "pear basket 2", 
    4 => "apple basket 2", 
    5 => "orange basket 2", 
    6 => "pear basket 3", 
    7 => "apple basket 3", 
    8 => "orange basket 3" 
);

我希望重新排列数组,使其以 n (本例中为3)的步长循环遍历旧数组,因此顺序变为:0,3,6,1 ,4,7,2,5,8。结果将是:

$array = (
    0 => "pear basket 1", 
    3 => "pear basket 2", 
    6 => "pear basket 3",
    1 => "apple basket 1",
    4 => "apple basket 2", 
    7 => "apple basket 3", 
    2 => "orange basket 1",
    5 => "orange basket 2", 
    8 => "orange basket 3" 
);

我浏览了所有PHP array functions,但仍然不知道该怎么做。

3 个答案:

答案 0 :(得分:1)

没有内置函数可以执行此操作(为什么人们期望执行此类特殊操作的预定义函数?)。它只是一个简单的嵌套循环。

$steps = 3;
$new_array = array();
for ($i = 0; $i < $steps; $i++) {
    for ($j = $i; $j < count($array); $j += $steps) {
        $new_array[$j] = $array[$j];
    }
}

答案 1 :(得分:1)

有时,一个人必须编写一个框架没有提供的代码,编码很快。

$array = array("pear basket 1", "apple basket 1", "orange basket 1", "pear basket 2", "apple basket 2", "orange basket 2", "pear basket 3", "apple basket 3", "orange basket 3" );

$newArray = array();


for ($i=0; $i < 3; $i++) { 
    for ($j=0; $j < 9; $j+=3) { 
        array_push($newArray, $array[($i+$j)]);
    }
}

答案 2 :(得分:0)

这是一个略有不同的看法

$array = array(
    0 => "pear basket 1",
    1 => "apple basket 1",
    2 => "orange basket 1",
    3 => "pear basket 2",
    4 => "apple basket 2",
    5 => "orange basket 2",
    6 => "pear basket 3",
    7 => "apple basket 3",
    8 => "orange basket 3"
);

$len=sizeof($array)-1;

$steps=3;
$new=$array;
foreach ($array as $k=>$v) {
    if ($k==$len) {
        break;
    }
    $newk=($k*$steps)%$len;
    $new[$newk]="$v";
}
ksort($new);

var_dump($new);