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条)

报告相同问题?

悬赏问题

  • ¥20 fluent无法启动
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥50 Oracle Kubernetes服务器集群主节点无法访问,工作节点可以访问
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架
  • ¥15 有关sql server business intellige安装,包括SSDT、SSMS。