如何将数组值最后更改为第3位?

时间:2019-02-21 10:05:31

标签: php arrays sorting

阵列位置是否可能发生变化?

我有类似数组

  [files] => Array
    (
        [name] => Array
            (
                [0] => file 1
                [1] => file 2
                [2] => file 3
            )

        [size] => Array
            (
                [0] => 1
                [1] => 2
                [2] => 3
            )

        [error] => Array
            (
                [0] => abc
                [1] => def
                [2] => ghi
            )
       [position] => Array
            (
                [0] => left
                [1] => right
                [2] => center
            )
      [details] => Array
            (
                [0] => detail1
                [1] => detail2
                [2] => detail3
            )
    )

我希望将数组值“ Details”移到错误之前大小旁边的第3个位置。 通过PHP可以实现吗?

1 个答案:

答案 0 :(得分:0)

是的,有可能我有时也喜欢使用类似的东西。看看下面的函数,它会做您想要的:

/** Easily append anywhere in associative arrays
 * @param array      $arr          Array to insert new values to
 * @param string|int $index        Index to insert new values before or after
 * @param array      $value        New values to insert into the array
 * @param boolean    $afterKey     Insert new values after the $index key
 * @param boolean    $appendOnFail If key is not present, append $value to tail of the array
 * @return array
 */
function arrayInsert($arr, $index, $value, $afterKey = true, $appendOnFail = false) {
    if(!isset($arr[$index])) {
        if($appendOnFail) {
            return $arr + $value;
        } else {
            echo "arrayInsert warning: index `{$index}` does not exist in array.";
            return $arr;
        }
    } else {
        $index = array_search($index, array_keys($arr)) + intval($afterKey);
        $head = array_splice($arr, $index);
        return $arr + $value + $head;
    }
}

示例结果:

>>> $test = ['name'=>[], 'size'=>[], 'error'=>[], 'position'=>[], 'details'=>[]];
=> [
     "name" => [],
     "size" => [],
     "error" => [],
     "position" => [],
     "details" => [],
   ]
>>> arrayInsert($test, 'size', ['details'=>$test['details']]);
=> [
     "name" => [],
     "size" => [],
     "details" => [],
     "error" => [],
     "position" => [],
   ]