如何以给定的格式填充数组?

我想形成一个像这样的数组:


$routes = [

            array("key" => 0, "title" => "All"),

            array("key" => 1, "title" => "Web Series"),

            array("key" => 2, "title" => "Reality Shows"),

            array("key" => 3, "title" => "Singing"),

            array("key" => 4, "title" => "Vendors")

        ];

在这里,标题(网络连续剧、真人秀、歌唱)应该来自数据库的响应:


    $projectTypes = ProjectType::select('project_type_title')->get()->all();

如何使用这些值填充像上面这样的数组?


笔记:


array("key" => 0, 

      "title" => "All") 

必须预定义并且不从数据库中获取,只有其他项目类型才会从数据库中获取。我的数据库包含以下值:


array ( 0 => 'Web series', 1 => 'Drama', 2 => 'Movie', )


慕后森
浏览 122回答 1
1回答

GCT1015

请随意使用下面的示例   $projectTypes = [array("key" => 1, "title" => "Web Series"),        array("key" => 2, "title" => "Reality Shows"),        array("key" => 3, "title" => "Singing"),        array("key" => 4, "title" => "Vendors")];$routes = [["key" => 0,       "title" => "All"]];foreach ($projectTypes as $value) {    $routes[] = ["key" => $value['key'], "title" => $value['title']];}结果:Array ( [0] => Array ( [key] => 0 [title] => All )         [1] => Array ( [key] => 1 [title] => Web Series )         [2] => Array ( [key] => 2 [title] => Reality Shows )         [3] => Array ( [key] => 3 [title] => Singing )         [4] => Array ( [key] => 4 [title] => Vendors ) )编辑:$projectTypes = ProjectType::select('project_type_title')->get()->all();$finalResult= [["key" => 0,       "title" => "All"]];foreach ($projectTypes as $key => $value) {    $finalResult[] = ["key" => $key + 1, "title" => $value];}
打开App,查看更多内容
随时随地看视频慕课网APP