PHP - 将数组重组为另一个数组

时间:2015-05-25 17:19:15

标签: php html arrays sorting indexing

我有这个数组:

Array ( [7] => 44 [6] => 45 [4] => 46 [1] => 47 [2] => 48 [8] => 49 [5] => 50 [3] => 51 ) 

我想创建另一个数组(或组织这个数组),以便获得以下数组:

Array ( [1] => 47 [8] => 49 [2] => 48 [7] => 44 [3] => 51 [6] => 45 [4] => 46 [5] => 50 ) 

基本上:

[Lowest index] => [Highest index]
[Second lowest index] => [Second highest index]
[Third lowest index] => [Third highest index]
[Fourth lowest index] => [Fourth highest index]

我需要这种重组是自动的,并且可以使用不同大小的数组。

2 个答案:

答案 0 :(得分:0)

我不知道这里是否有人会为你编写代码。人们喜欢看到你自己努力,然后询问你何时遇到问题。

但要指出正确的方向:查看array_keys()array_values()功能。然后使用它们来拆分数组,并对两个数组进行排序(一个包含键,一个包含值)。最后,根据需要使用array_combine()再次组合数组。

答案 1 :(得分:0)

好的,已经完成了。这就是我所做的:

$arrayPos1 = array();
$posi = 3;
$parti = 2;

//Building first array with seeds 1, 3, 5 and 7
$arrayPos1[1] = $arrayPart[1];
for($i=1;$i <= (count($arrayPart) / 2 - 1);$i++){
    $arrayPos1[$posi] = $arrayPart[$parti];
    $posi = $posi + 2;
    $parti = $parti + 1;
}
$arrayPos2 = array();
$posi = 2;
$parti = count($arrayPart);

//Building second array with seeds 2, 4, 6 and 8
for($i=1;$i <= (count($arrayPart) / 2 );$i++){
    $arrayPos2[$posi] = $arrayPart[$parti];
    $posi = $posi + 2;
    $parti = $parti - 1;
}

//Checking out the results
print_r($arrayPos1);
echo "<br>";
ksort($arrayPos2);
print_r($arrayPos2);
echo "<br>";

//Building final array
for($i=2;$i <= (count($arrayPart));$i=$i+2){
    $arrayPos1[$i] = $arrayPos2[$i];
}

//Sorting final array
ksort($arrayPos1);

这应该使得现在更容易生成表格。 谢谢你们的帮助:)