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

前端 未结 13 1545
余生分开走
余生分开走 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:41

    A simple approach to this is to iterate through the original array, constructing a new one as you go:

    function InsertBeforeKey( $originalArray, $originalKey, $insertKey, $insertValue ) {
    
        $newArray = array();
        $inserted = false;
    
        foreach( $originalArray as $key => $value ) {
    
            if( !$inserted && $key === $originalKey ) {
                $newArray[ $insertKey ] = $insertValue;
                $inserted = true;
            }
    
            $newArray[ $key ] = $value;
    
        }
    
        return $newArray;
    
    }
    

    Then simply call

    $array = InsertBeforeKey( $array, 'd', 'c', 3 );
    
    0 讨论(0)
提交回复
热议问题