Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何将最后一个数组值更改为第三个位置?_Php_Arrays_Sorting - Fatal编程技术网

Php 如何将最后一个数组值更改为第三个位置?

Php 如何将最后一个数组值更改为第三个位置?,php,arrays,sorting,Php,Arrays,Sorting,阵列位置是否有任何可能的变化 我有一个数组 [files] => Array ( [name] => Array ( [0] => file 1 [1] => file 2 [2] => file 3 ) [size] => Array (

阵列位置是否有任何可能的变化

我有一个数组

  [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”在出现错误之前移动到size旁边的第三个位置。
通过PHP它是可能的???

是的,它是可能的,曾经有一段时间我也喜欢使用类似的东西。看看下面的函数,这将实现您想要的功能:

/** 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" => [],
   ] 

可能是重复的嗯这么做有什么意义?