首页 > 解决方案 > 如何将最后一个数组值更改为第三个位置?

问题描述

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

我有类似的数组

  [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
            )
    )

我希望数组值“详细信息”移动到错误前大小旁边的第三个位置。可以通过PHP吗??

标签: phparrayssorting

解决方案


是的,有可能,曾经有一段时间我更喜欢使用这样的东西。看看下面的函数,它会做你想要的:

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

推荐阅读