将一维数组与多维数组相结合

时间:2015-10-12 19:46:48

标签: php arrays

我试图将一维数组与多维数组相结合。我看到有一个array_combine函数和一个array_merge函数,但它们似乎没有给我我需要的结果。我有以下数组:

$days = Array ( 
    [0] => Array ( 
        [0] => 3 
        [1] => 6 
    ) 
    [1] => Array ( 
        [0] => 6 
        [1] => 12 
    ) 
    [2] => Array ( 
        [0] => 2 
        [1] => 4 
    )
)

$names = Array ( 
    [0] => Joe Smith 
    [1] => John Doe 
    [2] => Jack Frost
)

这是我在使用array_merge($days,$names)时得到的结果:

$result = Array ( 
    [0] => Array ( 
        [0] => 3 
        [1] => 6 
    ) 
    [1] => Array ( 
        [0] => 6 
        [1] => 12 
    ) 
    [2] => Array ( 
        [0] => 2 
        [1] => 4 
    ) 
    [3] => Joe Smith 
    [4] => John Doe 
    [5] => Jack Frost 
)

如何获得以下结果:

$result = Array ( 
    [0] => Array (
        [0] => John Smith
        [1] => Array ( 
            [0] => 3 
            [1] => 6
        )
    ) 
    [1] => Array (
        [0] => John Doe
        [1] => Array ( 
            [0] => 6 
            [1] => 12 
        )
    ) 
    [2] => Array (
        [0] => Jack Frost
        [1] => Array ( 
            [0] => 2 
            [1] => 4 
        )
    )
)

有什么想法吗?感谢

1 个答案:

答案 0 :(得分:2)

使用array_map() $result = array_map(null, $names, $days); 中的示例#4,这是一个很酷的方法:

/*
     * This is for when we run the jar file
     */
    @Bean
    public ITemplateResolver defaultTemplateResolver() {
        final TemplateResolver resolver = new FileTemplateResolver();
        resolver.setSuffix(".html");
        resolver.setPrefix("src/main/resources/templates/");
        resolver.setTemplateMode("HTML5");
        resolver.setCharacterEncoding("UTF-8");
        resolver.setCacheable(false);
        return resolver;
    }