制作关联数组-array_combine()期望参数1为数组,给定字符串

时间:2018-10-29 10:36:39

标签: php arrays

我正在尝试创建一个关联数组,其中第一个元素将代表标题。

我想要这个数组:

Array
(
    [0] => Name,Phone number
    [1] => John,555666123
    [2] => Bobby McQueen, 556699887
)

并将其转换为以下数组:

Array
(
    [0] => Array
        (
            [Name] => John
            [Phone number] => 555666123
        )

    [1] => Array
        (
            [Name] => Bobby McQueen
            [Phone number] => 556699887
        )
)

这是我的代码

$assoc_array = array();
$my_array = explode("\n", file_get_contents($file->getPathName()));

$header = array_shift($my_array);


foreach ($my_array as $row) {
  $assoc_array[] = array_combine($header, $row);
}

但是我遇到了错误:

  

array_combine()期望参数1为数组,给出字符串

2 个答案:

答案 0 :(得分:2)

$assoc_array = array();
$my_array = explode("\n", file_get_contents($file->getPathName()));

$header = array_shift($my_array);
// $header is a string now "Name,Phone number"
// make it array:
$header = explode(",", $header);

foreach ($my_array as $row) {
  // $row is a string too, and should be exploded
  $assoc_array[] = array_combine($header, explode(',', $row));
}

但是正如注释中已经提到的那样-使用fgetcsv,它具有您当前代码未实现的某些功能。它还减少了代码行。

答案 1 :(得分:1)

您需要同时$header explode() $row,

$header = explode(',',array_shift($my_array));//convert header into array


foreach ($my_array as $row) {
  //combine header and $row which also become an array after explode()
  $assoc_array[] = array_combine($header, explode(','$row));
}