首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何显示包含相同值的键?

如何显示包含相同值的键?
EN

Stack Overflow用户
提问于 2016-02-07 22:35:15
回答 3查看 33关注 0票数 0

我目前正纠结于如何显示包含相同值的键。

我有一个包含键和值的数组,只有当数组中有重复的值时,我才使用语句if(array_count_values($arr) > 1)来打印。但是,我不知道如何打印重复的值键。

代码语言:javascript
复制
 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

EN

回答 3

Stack Overflow用户

发布于 2016-02-07 22:47:53

代码语言:javascript
复制
$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
EN

Stack Overflow用户

发布于 2016-02-07 22:58:35

我添加了另一个文件,以使其更有趣:

代码语言:javascript
复制
$input = [
    "test1.php" => 130313,
    "test2.php" => 130333,
    "test3.php" => 130313,
    "test4.php" => 140393,
    "test5.php" => 130333,
];

这个简单的解决方案首先准备一个从inode到文件的映射,然后“遍历”输入数组,根据inode对文件进行分区:

代码语言:javascript
复制
$inode_map = array_fill_keys(array_values($input), []);
array_walk($input, function ($inode, $file) use (&$inode_map) {
    $inode_map[$inode][] = $file;
});

$inode_map现在包含:

代码语言:javascript
复制
Array
(
    [130313] => Array
        (
            [0] => test1.php
            [1] => test3.php
        )

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

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

如果要查找重复的文件/信息节点,可以过滤映射:

代码语言:javascript
复制
$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
EN

Stack Overflow用户

发布于 2016-02-07 23:39:15

尝尝这个!

代码语言:javascript
复制
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>";
        }
    }    
}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35254759

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档