如何在PHP中按值获取所有键的数组?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (29)

如何转换这个数组:

$details = ["Dog" => "Natahlia", "Cat" => "Ryan", "Bird" => "Natahlia"];

转到这个(期望的输出):

$details = [["Natahlia"=>["Dog","Bird"], "Ryan"=>"Cat"];

由于我的代码连接了值或覆盖它,所以出现了一些问题。

$arr = array();
foreach($details as $key => $value){
   if(array_key_exists($value,$arr)){
      //this part i dont know what to do since += wont do it since it's a string and .= concatenates it
      $arr[$value] = $key;
   } else {
      $arr[$value] = $key;
   }
}
return $arr;
提问于
用户回答回答于

你在代码段中犯的错误是会覆盖$arr[$value]它已存在的时间。尝试以数组的形式附加它:

foreach ($details as $key => $value) {
   if (!isset($arr[$value])) {
      // $arr[$value] not defined yet, we create array with 1st element:
      $arr[$value] = [$key];
   } else {
      // it already exists and it's an array, we append new value:
      $arr[$value][] = $key;
   }
}
用户回答回答于

无需循环整个数组。 你只需循环唯一名称并使用该名称执行array_intersect。 array_intersect将返回匹配的名称,键作为动物,所以array_keys,你得到你期望的。 这只会循环唯一的名称,因此它可能比循环整个数组更快。

$details = ["Dog" => "Natahlia", "Cat" => "Ryan", "Bird" => "Natahlia"];


foreach(array_unique($details) as $name){
    $new[$name] = array_keys(array_intersect($details, [$name]));
}
var_dump($new);

输出:

array(2) {
     ["Natahlia"] => array(2) {
            [0] => "Dog"
            [1] => "Bird"
    }
    ["Ryan"] => array(1) {
            [0] => "Cat"
    }
}

https://3v4l.org/paYRJ

扫码关注云+社区

领取腾讯云代金券