gpt4 book ai didi

php - 将数组与标题组合 - 获取空数组

转载 作者:可可西里 更新时间:2023-11-01 00:08:01 26 4
gpt4 key购买 nike

我正在尝试创建一个新数组,其中键是第一个数组的标题,值是所有其他数组,但结果我得到一个空数组。

这是我的初始数组

$reader = \Asan\PHPExcel\Excel::load('test.xls', function(\Asan\PHPExcel\Reader\Xls $reader){});

foreach ($reader as $row)
{
print_r($row);
}


Array
(
[0] => Phone
[1] => Sum
[2] => Name
[3] => Something else
)
Array
(
[0] => +1 555123456
[1] => 50.00
[2] => Johnny Doe
[3] => 100.50
)
Array
(
[0] => 911
[1] => 20.12
[2] => Eli the Computer Guy
[3] => 99.99
)

我试着像这样创建新数组

$row = 1; // header row
foreach ($reader as $row)
{
if ($row == 1)
{
$headers = $row;
}
else
{
$new_array[] = [
$headers => $row;
]
}

print_r($row); // prints empty array
}

我希望结果数组看起来像这样

Array
(
[0] => Array
(
[Phone] => +1 555123456
[Sum] => 50.00
[Name] => Johnny Doe
[Something else] => 100.50
)

[1] => Array
(
[Phone] => 911
[Sum] => 20.12
[Name] => Eli the Computer Guy
[Something else] => 99.99
)
)

最佳答案

您还可以使用 array_maparray_combine :

$headers = array_shift($arrays);
$result = array_map(function($x) use ($headers){
return array_combine($headers, $x);
}, $arrays);

Demo

关于php - 将数组与标题组合 - 获取空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53097233/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com