duanliang1019 2011-08-22 04:26
浏览 95
已采纳

如何防止array_merge重新编号数字键

i have an array which looks like this:

Array ( 
    [0] => Array ( [unit_id] => 1 [unit_name] => Clown Fish) 
    [1] => Array ( [unit_id] => L [unit_name] => Liter ) 
    [2] => Array ( [unit_id] => 2 [unit_name] => Elephant  ) 
    [3] => Array ( [unit_id] => 3 [unit_name] => Water Bottle ) 
    [4] => Array ( [unit_id] => 4 [unit_name] => Office Seating ) 
    [5] => Array ( [unit_id] => 5 [unit_name] => Green Green Grass ) 
)

then, i wrote a function

function array_to_list($arr_data, $str_key, $str_value) {
    $arr_list = array();
    if (is_array($arr_data)) {
        foreach($arr_data as $arr_value) {
            if (isset($arr_value[$str_key]) && isset($arr_value[$str_value])) {
                $arr_list = array_merge($arr_list, array($arr_value[$str_key] => $arr_value[$str_value]));
            }
        }
    }
    return $arr_list;
}

to convert the array to look like this

Array ( 
    [1] => Clown Fish ) 
    [L] => Liter ) 
    [2] => Elephant ) 
    [3] => Water Bottle ) 
    [4] => Office Seating ) 
    [5] => Green Green Grass ) 
)

but the output, instead, is

Array ( 
    [0] => Clown Fish ) 
    [L] => Liter ) 
    [1] => Elephant ) 
    [2] => Water Bottle ) 
    [3] => Office Seating ) 
    [4] => Green Green Grass ) 
)

i assume this has something to do with the nature of array_merge itself, which according to php manual "Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array."

is there a way to so i can produce the intended result with or without array_merge?

  • 写回答

3条回答 默认 最新

  • doujuanju3076 2011-08-22 04:42
    关注

    Why don't you just try a much simpler approach:

    function array_to_list($arr_data, $str_key, $str_value) {
        $arr_list = array();
        if (is_array($arr_data)) {
            foreach($arr_data as $arr_value) {
                if (isset($arr_value[$str_key]) && isset($arr_value[$str_value])) {
    
                    // This is the changed line:
                    $arr_list[ $arr_value[$str_key] ] = $arr_value[$str_value];
    
                }
            }
        }
        return $arr_list;
    }
    

    This just sets the values on the output array directly. There's no reason to make a new array and merge it each time. It also should be a bit faster.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换