2016-02-07 18 views
0

我目前一直在搞清楚如何顯示包含相同值的鍵。如何顯示包含相同值的鍵?

我有一個包含鍵和值的數組,我使用語句 if(array_count_values($arr) > 1)僅在數組中存在重複值時纔打印。但是我不知道如何打印重複的值鍵。

if(array_count_values($arr) > 1) { 
    echo "The following files are the same: \n"; 
} 

$ arr裏面有鍵和值。密鑰是文件名,值是它們的inode。

下面是一個例子陣列

[test1.php] => 130313 [test2.php] => 130333 [test3.php] => 130313 [test4.php] => 140393

我如何打印The following files are the same: test1.php, test2.php

+0

您的意思是test1和test3是一樣的嗎? – Michael

+0

是的,它們是相同的 –

+0

我不確定是否有直接的陣列功能來做你想做的。你只需要制定一個簡單的邏輯來做到這一點。 – CodeTweetie

回答

0
$histogram = array(); 
foreach ($arr as $k => $v) { 
    if (array_key_exists($v, $histogram)) { 
     $histogram[$v][] = $k; 
    } else { 
     $histogram[$v] = array($k); 
    } 
} 

foreach ($histogram as $keys) { 
    echo 'The following files are the same: ' . implode(', ', $keys) . "<br />\r\n"; 
} 

它應該工作,我只是編碼它沒有測試。我解決了你的問題嗎?

0

我添加了另一個文件,使之更加有趣:

$input = [ 
    "test1.php" => 130313, 
    "test2.php" => 130333, 
    "test3.php" => 130313, 
    "test4.php" => 140393, 
    "test5.php" => 130333, 
]; 

這種簡單的解決方案首先準備從索引節點的地圖文件,那麼「走出去」,通過輸入數組根據inode中的文件分區:

$inode_map = array_fill_keys(array_values($input), []); 
array_walk($input, function ($inode, $file) use (&$inode_map) { 
    $inode_map[$inode][] = $file; 
}); 

$inode_map現在包含:

Array 
(
    [130313] => Array 
     (
      [0] => test1.php 
      [1] => test3.php 
     ) 

    [130333] => Array 
     (
      [0] => test2.php 
      [1] => test5.php 
     ) 

    [140393] => Array 
     (
      [0] => test4.php 
     ) 
) 

如果你想查找重複的文件/ inode,你可以過濾地圖:

$duplicates_only = array_filter($inode_map, function ($files) { 
    return count($files) > 1; 
}); 

foreach ($duplicates_only as $inode => $files) { 
    echo "The following files are the same ($inode): " . join(", ", $files) . PHP_EOL; 
} 
+0

如果你喜歡這種語法,你可以用'foreach'代替'array_walk' – Michael

-1

試試這個!

foreach ($arr as $file1=>$value1){ 
    foreach ($arr as $file2=>$value2){ 
     if($file1!=$file2 && $value1==$value2){ 
      echo "<p>The following files are the same: $file1 =>$value1, $file2=>$value2 </p>"; 
     } 
    }  
} 
+0

如果有三個相同的文件,這個解決方案將顯示三行,每行兩個文件。撲朔迷離 – Michael

相關問題