项目场景:
每一列对应是一条数据,并设置对应key值
解决方案:
JS方案
let list = [
["腾讯", "百度", "阿里巴巴","美团"],
[100, 200, 300,400],
[10000, 20000, 30000,40000],
[9, 99, 999,9999],
[6, 66, 666,6666]
]
let header = ['公司', '2020-12-31', '2021-06-30','成分','流利程度']
let result = header.reduce( (obj, key, i) => {
obj[i] = list.map(item => item[i]);
// console.log(obj[i])
// ["腾讯", 100, 1000];
obj[i] = header.reduce( (obj2, key, index) => {
obj2[key] = obj[i][index];
return obj2;
}, {})
console.log(i)
// {公司: "腾讯", '2020-12-31': 100, '2021-06-30': 10000, 成分: 9, 流利程度: 6}
if(i>(list[0].length-1)){ delete obj[i]; }
return obj;
}, [])
console.log(result);
// [
// {公司: "腾讯", '2020-12-31': 100, '2021-06-30': 10000, 成分: 9, 流利程度: 6},
// {公司: "百度", '2020-12-31': 200, '2021-06-30': 20000, 成分: 99, 流利程度: 66},
// {公司: "阿里巴巴", '2020-12-31': 300, '2021-06-30': 30000, 成分: 999, 流利程度: 666},
// {公司: "美团", '2020-12-31': 400, '2021-06-30': 40000, 成分: 9999, 流利程度: 6666}
// ]
PHP方案
<?php
header("Content-type:text/html;charset=utf-8");
$list = [
["腾讯", "百度", "阿里巴巴","美团"],
[100, 200, 300,400],
[10000, 20000, 30000,40000],
[9, 99, 999,9999],
[6, 66, 666,6666]
];
$header = ['公司', '2020-12-31', '2021-06-30','成分','流利程度'];
$list2 = [];
for ($i=0; $i < count($list[0]); $i++) {
$list2[] = array_combine($header, array_column($list, $i));
}
echo "<pre>";
print_r($list2);
echo "<pre>";
备注
仅供参考,具体情况可能不同,请自行领悟。