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

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

    You can define your own sortmap when doing a bubble-sort by key. It's probably not terribly efficient but it works.

    1,'z'=>2,'d'=>4);
    
    $array['c'] = 3;
    
    print_r( $array );
    
    uksort( $array, 'sorter' );
    
    print_r( $array );
    
    function sorter( $a, $b )
    {
        static $ordinality = array(
            'a' => 1
          , 'c' => 2
          , 'z' => 3
          , 'd' => 4
        );
        return $ordinality[$a] - $ordinality[$b];
    }
    
    ?>
    

    Here's an approach based on ArrayObject using this same concept

    $array = new CitizenArray( array('a'=>1,'z'=>2,'d'=>4) );
    $array['c'] = 3;
    
    foreach ( $array as $key => $value )
    {
        echo "$key: $value 
    "; } class CitizenArray extends ArrayObject { static protected $ordinality = array( 'a' => 1 , 'c' => 2 , 'z' => 3 , 'd' => 4 ); function offsetSet( $key, $value ) { parent::offsetSet( $key, $value ); $this->uksort( array( $this, 'sorter' ) ); } function sorter( $a, $b ) { return self::$ordinality[$a] - self::$ordinality[$b]; } }

提交回复
热议问题