首页 > 解决方案 > Laravel如何遍历数组并按键获取值

问题描述

在我的laravel应用程序中,我有两个数组,一个称为“headers”,一个称为“rows”,我只想要“row”数组中的数据,它基于“headers”数组中的键。

所以这是我的数组:

  "rows" => array:2 [
     0 => array:6 [
        "Company name" => "Universal"
        "Address" => "Some address"
        "Zipcode" => 12122
        "City" => "Some city"
        "Phonenumber" => 12345678
        "Email" => "mail@mail.com"
     ],
     1 => array:6 [
        "Company name" => "Warner Bros."
        "Address" => "another address"
        "Zipcode" => 12122
        "City" => "city abc"
        "Phonenumber" => 12345678
        "Email" => "mail2@mail.com"
     ]

  ],
  "headers" => array:4 [
     0 => array:2 [
       "name" => "Company name"
       "data" => array:1 [
          "value" => "company_name"
       ]
     ],
     1 => array:2 [
      "name" => "Adresse"
      "data" => array:1 [
         "value" => "address"
      ]
    ]
  ]

到目前为止一切顺利,现在我只想要从“headers”数组中选择的“rows”数组中的数据,这样我就可以在前端这样显示它们:

Company name    |    Address
----------------------------------
Universal       |    Some address
Warner Bros.    |    Another address

那么,如何将它们存储在数据库中呢?我的模型结构是这样的:

Entry::create([
    'company_name' => request()->company_name ?? null,
    'address' => request()->address ?? null,
    'zipcode' => request()->zipcode ?? null,
    'city' => request()->city ?? null,
    'number' => request()->number ?? null,
    'email' => request()->email ?? null
]);

提前致谢...

标签: phparrayslaravel

解决方案


嗨朋友先循环遍历公司数组,然后动态创建一个数组并将其传递给模型,如下所示

$data = $request->rows;
$columns = $request->headers;

foreach($data as $item){

  $array_of_items = [] 
  
  foreach($columns as $column){
     
     $column_name = $column['name']; //should return "Company Name"      

     if($item[$column_name]){ // means has the value
       $column_code = $column['data']['value'] //should return "company_name" in first loop and so on, if not cannot carry on
       $array_of_items[$column_code] = $item[$column_name];
     }
     
  }

  if(!empty($array_of_items)){
     Entry::create($array_of_items);
  }


}

如果有任何疑问,请随时发表评论,谢谢您有美好的一天。


推荐阅读