如何在php(laravel5)中创建多个数组?

时间:2017-10-23 05:54:06

标签: php arrays laravel

我想用php制作多个数组(laravel5) 有两个数组如下。

$tags=['en' =>[]];
$TAGS = ['test1','test2','test3',...]

我想在某些代码中将此数组作为返回值,如下所示:

return [
    'tags' => [
        'en' => [
            'test1' => 'test1',
            'test2' => 'test2',
            'test3' => 'test3',
            ...
        ]
    ]
]

我尝试了以下操作,但它没有用。

return [
    'tags' => [
        'en' => [
            foreach($TAGS as $TT)
                array_push($tags['en'], $TT);
        ]
    ]
]

还有其他方法吗?
请你的建议。感谢。

2 个答案:

答案 0 :(得分:0)

试试这样:

<?php
$mainArray = array("EN","IT","SP"....);
$returnArray = array();
foreach($mainArray as $key => $value){
    //Create the sub array here as you want it.
    $subArray = [
        "Test1" => "test1",
        "Test2" => "test2",
        "Test3" => "test3"
    ];        
    array_push($returnArray[$value],$subArray);
}

return $returnArray;
?>

答案 1 :(得分:0)

试试这个 -

$json = array();
$langs = ['en','fr'];
$tags = ['test1','test2','test3'];
 foreach ($langs as $lang) {
    $json[$lang] = [];
    foreach ($tags as $tag) {
        $json[$lang][] = $tag;
    }
 }
return $json;