为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
慕后森 2023-06-30 16:07:24
我想形成一个像这样的数组:$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', )
查看完整描述

1 回答

?
GCT1015

TA贡献1827条经验 获得超4个赞

请随意使用下面的示例


   $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];

}


查看完整回答
反对 回复 2023-06-30
  • 1 回答
  • 0 关注
  • 121 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信