PHP是另一个多维关联数组问题
我知道这就在眼前,但我需要向数组的每一行添加一个元素 我有这个阵列:PHP是另一个多维关联数组问题,php,arrays,multidimensional-array,Php,Arrays,Multidimensional Array,我知道这就在眼前,但我需要向数组的每一行添加一个元素 我有这个阵列: Array ( [0] => Array ( [Elements] => values ) [1] => Array ( [Elements] => values ) ) 现在,我想在每个元素的末尾添加一个元素,该元素保存原始数据的文件名 发生这种情况的代码部分位于类方法中,用于查找数据库中已有的重复项。如果它是重复的,我们将$file
Array (
[0] => Array (
[Elements] => values
)
[1] => Array (
[Elements] => values
)
)
现在,我想在每个元素的末尾添加一个元素,该元素保存原始数据的文件名
发生这种情况的代码部分位于类方法中,用于查找数据库中已有的重复项。如果它是重复的,我们将$fileData迭代添加到$duplicates数组中,该数组将返回给调用函数。基本上是这样的:
while($data = fgetcsv($handle)) {
$leadDataLine = array_combine($headers, $data);
// Some data formatting on $leadDataLine not important for this question...
// Add the line to the stack
$leadData[] = $leadDataLine;
//array_push($leadData, $leadDataLine);
unset($leadDataLine);
}
$dup[] = $lead->process($leadData);
潜在客户类别:
<?php
public function process(&$fileData) {
$duplicates = array();
// Process the information
foreach($fileData as $row) {
// If not a duplicate add to the database
if (!$this->isDuplicate($row)) {
// Add the lead to the database.
$this->add($row);
} else {
// is a duplicate, add to $dup
$duplicates[] = array("Elements" => $row['Values']);
/*
* Here is where I want to add the file name to the end of $duplicates
* This has to be here because this class handles different sources of data,
* Not all data will have a FileName key
*/
if (array_key_exists("FileName", $row))
$duplicates["FileName"] = $row["FileName"];
// array_push($duplicates, $row["FileName"]);
}
}
print_r($duplicates);
return $duplicates;
}
注意,它不在元素1上
我做错了什么。如果你做错了
$x[] = 'yo'
您正在将值推送到数组的顶层。如果要将新项推送到该数组的子元素上,则必须显式说明哪个子元素:
$x[0][] = 'yo';
索引是唯一的。根据您的代码,看起来您一直在覆盖$duplicates['filename'],这样只存储最后一个文件名。伙计,我没有了!哈我试过$x[][“文件名”]。。只需添加一个变量来跟踪迭代并运行良好…ThanksI将其更改为$duplicates[$line][“FileName”]=$row[“FileName”];其中,每次重新启动foreach循环时,行计数。。。那应该能解决这个问题,对吗?
$x[0][] = 'yo';