How to add an array value to the middle of an associative array?

前端 未结 13 1639
余生分开走
余生分开走 2020-12-08 00:36

Lets say I have this array:

$array = array(\'a\'=>1,\'z\'=>2,\'d\'=>4);

Later in the script, I want to add the value \'c\'=>3<

13条回答
  •  轮回少年
    2020-12-08 01:35

    For the moment the best i can found to try to minimize the creation of new arrays are these two functions :

    the first one try to replace value into the original array and the second one return a new array.

    // replace value into the original array
    function insert_key_before_inplace(&$base, $beforeKey, $newKey, $value) {
     $index = 0;
     foreach($base as $key => $val) {
        if ($key==$beforeKey) break;
        $index++;
     }
     $end = array_splice($base, $index, count($base)-$index);
     $base[$newKey] = $value;
     foreach($end as $key => $val) $base[$key] = $val;
    }
    
    
    $array = array('a'=>1,'z'=>2,'d'=>4);
    
    insert_key_before_inplace($array, 'z', 'c', 3);
    
    var_export($array); // array ( 'a' => 1, 'c' => 3, 'z' => 2, 'd' => 4, )
    

    // create new array
    function insert_key_before($base, $beforeKey, $newKey, $value) {
     $index = 0;
     foreach($base as $key => $val) {
        if ($key==$beforeKey) break;
        $index++;
     }
     $end = array_splice($base, $index, count($base)-$index);
     $base[$newKey] = $value;
     return $base+$end;
    }
    
    
    $array = array('a'=>1,'z'=>2,'d'=>4);
    
    $newArray=insert_key_before($array, 'z', 'c', 3);
    
    var_export($array); // ( 'a' => 1, 'z' => 2, 'd' => 4, )
    
    var_export($newArray); // array ( 'a' => 1, 'c' => 3, 'z' => 2, 'd' => 4, )
    

提交回复
热议问题