PHP的另一个多维关联数组问题 [英] PHP Yet another Multidimensional Associative Array problem
问题描述
我知道这就在我眼前,但是我需要向数组的每一行添加一个元素。
I know this is right in front of me, but I need to add an element to each row of an array..
我有这个数组:
Array (
[0] => Array (
[Elements] => values
)
[1] => Array (
[Elements] => values
)
)
现在,我想在每个元素的末尾添加一个元素,以保存原始数据的文件名。
Now, I want to add an element to the end of each one that holds the file name of the originating data.
这部分代码位于类方法中,以查找数据库中已存在的重复项。如果是重复项,则将$ fileData迭代添加到$ duplicates数组中,该数组将返回给调用函数。基本上看起来像这样:
The part of code this takes place in, is in a class method to look for duplicates already in the database. If it is a duplicate, we add the $fileData iteration to the $duplicates array which gets returned to the calling function. It basically looks like this:
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;
}
我拥有的代码或使用array_push会发生什么:
What happens with the code I have, or using array_push:
Array (
[0] => Array (
[Elements] => values
)
[FileName] => correct_file.csv
[1] => Array (
[Elements] => Values
)
)
注意,它不在元素1上。
Notice, it is not on element 1..
我在这里做什么错了。
推荐答案
如果您这样做
$x[] = 'yo'
您将值推入了数组的顶层。如果要将新项目推送到此数组的子元素上,则必须明确声明哪个子元素:
you're pushign a value onto the top level of the array. If you want push a new item onto a sub-element of this array, you have to explicitly state which sub-element:
$x[0][] = 'yo';
这篇关于PHP的另一个多维关联数组问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!