PHP combine_array 当元素数相同时产生 false

PHP combine_array produces false when element count is the same

如果这个问题与其他问题很接近,我们深表歉意。我已经尝试了所有解决方案来完成一些简单的事情,但失败了。 :-(

我希望将数组一中的键指定为数组二的键。

$demos_keys = array_keys($demos);

//$c = array_combine($demos_keys, $csvdata); produces "FALSE"
//$c = $demos_keys +  $csvdata; simply adds the arrays but doesn't assign keys

So then I tried to loop through each element to assign the keys manually - to no avail! 

foreach ($csvdata as $row){
     for($i = 0; $i<count($demo_keys); $i++) {
        $csvdata[$demo_keys[$i]]=$row[$i];
     } 
}

demos_keys: 姓氏”:“姓氏”,“电子邮件”:“电子邮件”,“d1”:“phone”,“d2”:“状态”

csv数据: "Dryer,fdryer@email.com,Backfield,North\r","Harris,fharris@email.com,Corp,South\r",等等

我觉得 csvdata 数组有点不稳定。每件事都说它是一个大约有 1000 行的数组,但最后一个元素末尾的回车 return 让我很困扰。我想我以后再处理。

我还能尝试什么!?感谢大家的贡献!

您的 CSV 数据的每一行似乎都没有被解析为单独的变量(您是否使用 fgetsfile 而不是 fgetcsv 从文件中读取它?) .所以你需要先拆分它,然后才能将它与 $demos_keys 中的键组合。这样的事情应该有效:

$demos_keys = array("lastname","email","d1","d2");
$csvdata = array("Dryer,fdryer@email.com,Backfield,North\r","Harris,fharris@email.com,Corp,South\r");

$result = array();
foreach ($csvdata as $row) {
    $data = explode(',', trim($row));
    $result[] = array_combine($demos_keys, $data);
}
print_r($result);

输出:

Array
(
    [0] => Array
        (
            [lastname] => Dryer
            [email] => fdryer@email.com
            [d1] => Backfield
            [d2] => North
        )
    [1] => Array
        (
            [lastname] => Harris
            [email] => fharris@email.com
            [d1] => Corp
            [d2] => South
        )
)

Demo on 3v4l.org