交换数组键位置

时间:2017-06-28 21:43:01

标签: php arrays sorting swap

我需要交换数组键 这就是我所拥有的

  Array
  (
    [0] => file1.pdf
    [1] => file2.pdf
    [2] => file3.pdf
    [3] => file4.pdf
    [4] => file5.pdf
    [5] => file6.pdf
  )

这就是我需要的东西

  Array
  (
    [1] => file2.pdf
    [0] => file1.pdf
    [3] => file4.pdf
    [2] => file3.pdf
    [5] => file6.pdf
    [4] => file5.pdf
  )

我不知道阵列有多大,但阵列总是均匀的。 有人可以帮我解决这个问题。

2 个答案:

答案 0 :(得分:0)

就是这样,希望它会有所帮助。

首先我们创建新数组,我们将新的有序数据放入其中。接下来,我们将遍历旧数组并将自定义数据放入$ newArr。

<?php

$arr = array("file1.pdf", "file2.pdf", "file3.pdf", "file4.pdf", "file5.pdf", "file6.pdf");
$newArr = [];

$a = 0;
$arrCount = count($arr);

while (count($newArr) !== $arrCount) {
    $newArr[$a + 1] = $arr[$a + 1];
    $newArr[$a] = $arr[$a];
    $a = $a  +  2;
}

// Old array
print_r($arr);

// New array
print_r($newArr);

答案 1 :(得分:-1)

<?php
$array=Array
  (
    "file1.pdf",
    "file2.pdf",
    "file3.pdf",
    "file4.pdf",
    "file5.pdf",
    "file6.pdf"
  );
  $newarray=[];
  foreach ($array as $key => $value) {
      if($key & 1){
        $newarray[]=$array[$key];
        $newarray[]=$array[$key-1];
      }
  }
  array_push($newarray,$array[count($array)-1];
  $newarray=array_unique($newarray);
  echo "<pre>";
  print_r($newarray);
  echo "</pre>";
  ?>