【问题标题】:Missing values from the same key after using array_flip function [duplicate]使用array_flip函数后来自同一键的缺失值[重复]
【发布时间】:2018-05-14 11:51:43
【问题描述】:

我正在尝试翻转数组,但它错过了同名键的值。 我必须使用什么来向数组中多次出现的键添加几个值?

例如,对于

[
    "Input.txt" => "Randy",
    "Code.py" => "Stan",
    "Output.txt" => "Randy"
]

groupByOwners 函数应该返回

[
    "Randy" => ["Input.txt", "Output.txt"],
    "Stan" => ["Code.py"]
]

当前代码:

class FileOwners
{
    static $files;
    public static function groupByOwners($files)
    {
       $flip = array_flip($files);
        print_r($flip);
    }
}

    $files = array
    (
        "Input.txt" => "Randy",
        "Code.py" => "Stan",
        "Output.txt" => "Randy"
    );

我的函数返回Array ( [Randy] => Output.txt [Stan] => Code.py ) NULL

因此缺少“Input.txt”值。这两个值必须是相同的键,那么如何将“Input.txt”和“Output.txt”放在键[Randy]的数组中?

【问题讨论】:

  • 欢迎来到 SO!好问题。您应该始终提供的一件事是期望的输出(类似于您提供$files 的方式)。答案可能会有所不同,具体取决于 all 数组元素是否可以成为值数组。
  • @cale_b 有点隐藏但是“groupByOwners 函数应该返回["Randy" => ["Input.txt", "Output.txt"], "Stan" => ["Code.py"]]

标签: php arrays function oop array-flip


【解决方案1】:

你必须自己循环它并构建一个新数组:

$files = array(
    "Input.txt" => "Randy",
    "Code.py" => "Stan",
    "Output.txt" => "Randy"
);

$new_files = array();

foreach($files as $k=>$v)
{
    $new_files[$v][] = $k;
}

print_r($new_files);

【讨论】:

  • 轻度警告,可能不是问题 - 但如果值为 NULLisset 将返回 FALSE。
  • 您的array_key_exists 语法是错误的,但您不需要它也不需要if 语句,您可以简单地在循环中使用$new_files[$v][] = $k;。无需初始化数组中的数组。
  • @jeroen 有时,我忘记了 PHP 具有如此宽容的结构。非常感谢您的反馈。
  • 好的,现在我明白了。谢谢你的帮助!作为初学者,这对我来说既简单又不稳定。我看到了你发布的我的帖子。如有错误,请记住下次如何正确发布问题。谢谢!
【解决方案2】:

一个有点快速和有点 hacky 的解决方案:

php >  $files = array
php >     (
php (         "Input.txt" => "Randy",
php (         "Code.py" => "Stan",
php (         "Output.txt" => "Randy"
php (     );
php > var_dump(array_reduce(array_keys($files), function($p, $c) use (&$files) { $p[$files[$c]] = $p[$files[$c]] ?? []; $p[$files[$c]][] = $c; return $p;  }, []));
array(2) {
  ["Randy"]=>
  array(2) {
    [0]=>
    string(9) "Input.txt"
    [1]=>
    string(10) "Output.txt"
  }
  ["Stan"]=>
  array(1) {
    [0]=>
    string(7) "Code.py"
  }
}

注意:使用 '??'需要 PHP 7.0。

只是为了将重要部分从单行中提取出来并使其至少更具可读性:

array_reduce(array_keys($files), function($p, $c) uses (&$files) {
     $p[$files[$c]] = $p[$files[$c]] ?? []; 
     $p[$files[$c]][] = $c;
}, []);

您可以轻松地使用 if(isset(...)) 逻辑来确保 $p 中的数组元素存在。

【讨论】:

  • 聪明,但不是很可读(可能部分是因为你已经把它全部放在一行上)。
  • 稍微提高了可读性!不过,简单的 for 循环可能总是更具可读性。
猜你喜欢
  • 1970-01-01
  • 2015-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多