如何转动此阵列:
$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;
答案 0 :(得分:5)
无需循环整个阵列
您只需要循环唯一的名称并使用该名称执行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"
}
}
答案 1 :(得分:0)
<?php
$details = ["Dog" => "Natahlia", "Cat" => "Ryan", "Bird" => "Natahlia"];
foreach($details as $animal => $name)
$result[$name][] = $animal;
var_export($result);
输出:
array (
'Natahlia' =>
array (
0 => 'Dog',
1 => 'Bird',
),
'Ryan' =>
array (
0 => 'Cat',
),
)