php - 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
]);
提前致谢...
解决方案
嗨朋友先循环遍历公司数组,然后动态创建一个数组并将其传递给模型,如下所示
$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);
}
}
如果有任何疑问,请随时发表评论,谢谢您有美好的一天。
推荐阅读
- java - 在java中关闭资源和使扫描仪私有有什么区别?
- r - 如何使用`renderMenu`在闪亮(shinydashboard)中动态添加额外的`sidebarMenu`?
- firebase - 通过 Github Actions 持续集成平台远程构建 Flutter 应用找不到 GoogleService-Info.plist 文件
- dynamics-crm - 无法单击动态 Web 应用程序主页上的应用程序
- java - 圆形进度条颜色不变(Android)
- azure - 设置云后无法从 Jenkins 预配 Azure VM
- windows - 如果我使用 CreateWindow*() 而不是 CreateDialog*() 函数系列,我会有什么“缺点”?
- reactjs - 我想用 React 在 div 元素中添加参数
- react-native - React: Uncaught SyntaxError: Unexpected token < in JSON at position 0
- sass - Bootstrap 5 - 使用 row-cols() mixin 时丢失列类功能