![](/img/trans.png)
[英]Removing duplicates from multidimensional array based on the first elements only PHP
[英]PHP code is removing duplicates from multidimensional array
我有一個.txt文件,如下所示:
Test = 10849831 = August 6, 2013:
56cake = 0 = August 6, 2013:
Wwe = 812986192 = August 6, 2013:
Test = 346192 = August 9, 2013:
然后,我使用以下PHP代碼...
$Output = array();
$Lines = explode(":", $txt);
foreach($Lines as $line) {
$Rows = array_map('trim', explode(" = ", $line));
if(!isset($Rows[0], $Rows[1], $Rows[2])) continue;
$Output[$Rows[0]] = array($Rows[1], $Rows[2]);
}
print_r($Output);
...將.txt文件轉換為多維數組,如下所示:
Array
(
[Test] => Array
(
[0] => 346192
[1] => August 9, 2013
)
[56cake] => Array
(
[0] => 0
[1] => August 6, 2013
)
[Wwe] => Array
(
[0] => 812986192
[1] => August 6, 2013
)
)
但是,有一個很大的錯誤。 該代碼刪除所有重復的數據值。 在我的示例txt文件中,我有兩個名為“Test”的值,但代碼只在多維數組中輸出ONE 。
您還可以注意到代碼如何使用最新的(“.txt”文件中的最后一行)替換第一個“Test”元素(在多維數組中)的數據。
數組中第一個“Test”元素的數據甚至不匹配.txt文件第一行中的數據Test = 10849831 = August 6, 2013:
。
我該如何解決這個問題? 我希望多維數組看起來像這樣:
Array
(
[Test] => Array
(
[0] => 10849831
[1] => August 6, 2013
)
[56cake] => Array
(
[0] => 0
[1] => August 6, 2013
)
[Wwe] => Array
(
[0] => 812986192
[1] => August 6, 2013
)
[Test] => Array
(
[0] => 346192
[1] => August 9, 2013
)
)
您不能在數組中使用相同的鍵兩次。 就這樣。
因此,當您添加“新”條目時,舊值將被覆蓋。
例:
$data = array("test" => "Content 1");
$data["test"] = "Content 2";
echo "<pre>" . print_r($data,1) . "</pre>";
//Will give you:
[test] => "Content 2"
你不能有相同的鑰匙。 在你的情況下測試。 我建議替代方案
foreach($Lines as $line) {
$Rows = array_map('trim', explode(" = ", $line));
if(!isset($Rows[0], $Rows[1], $Rows[2])) continue;
$Output[] = array('type'=>$Rows[0],'id'=>$Rows[1],'date'=> $Rows[2]);
}
類型,ID,日期; 在哪里我猜
正如其他人所指出的那樣,您的代碼無法提供所需的結果,因為數組不能包含相同的鍵,因此您的數據將被覆蓋。 Dagon的答案存儲了所有重復項,但是丟失了使用輸入文件每行的第一個元素進行鍵查找的能力。
保留鍵查找功能的替代方法是:
foreach($Lines as $line) {
$Rows = array_map('trim', explode(" = ", $line));
if(!isset($Rows[0], $Rows[1], $Rows[2])) continue;
if (array_key_exists($Rows[0], $Output))
$Output[$Rows[0]][] = array($Rows[1], $Rows[2]);
else
$Output[$Rows[0]] = array(array($Rows[1], $Rows[2]));
}
$ Output中的每個鍵都保存一個數組,而不是直接在每行中保存數據,每個行都有一個元素,文本文件中包含該鍵。 使用示例數據,生成的數組將如下所示:
Array
(
[Test] => Array
(
[0] => Array
(
[0] => 10849831
[1] => August 6, 2013
)
[1] => Array
(
[0] => 346192
[1] => August 9, 2013
)
)
[56cake] => Array
(
[0] => Array
(
[0] => 0
[1] => August 6, 2013
)
)
[Wwe] => Array
(
[0] => Array
(
[0] => 812986192
[1] => August 6, 2013
)
)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.