Add 2 values to 1 key in a PHP array

后端 未结 7 1027
面向向阳花
面向向阳花 2021-02-08 03:35

I have a result set of data that I want to write to an array in php. Here is my sample data:

**Name** **Abbrev**
Mike     M
Tom      T
Jim      J
7条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-08 04:12

    php arrays work like hash lookup tables, so in order to achieve the desired result, you can initialize 2 keys, one with the actual value and the other one with a reference pointing to the first. For instance you could do:

    $a = array('m' => 'value');
    $a['mike'] = &$a['m']; //notice the end to pass by reference
    

    if you try:

    $a = array('m' => 'value');
    $a['mike'] = &$a['m'];
    
    print_r($a);
    
    $a['m'] = 'new_value';
    print_r($a);
    
    $a['mike'] = 'new_value_2';
    print_r($a);
    

    the output will be:

    Array
    (
        [m] => value
        [mike] => value
    )
    Array
    (
        [m] => new_value
        [mike] => new_value
    )
    Array
    (
        [m] => new_value_2
        [mike] => new_value_2
    )
    

提交回复
热议问题