如何通过PHP中的值对关联数组进行分组?

时间:2018-07-24 07:27:29

标签: php associative-array

假设我有一个关联数组,如下所示:

src

如何在php中创建函数以返回一个按其值分组的关联数组,如下所示:

["dog" => "mammal", "cat" => "mammal", "snake" => "reptile"]

1 个答案:

答案 0 :(得分:2)

尝试一下:

// Your array
$array = ["dog" => "mammal", "cat" => "mammal", "snake" => "reptile"];

// Create a new array
$result = array();

// Loop through your array
foreach ($array as $animal => $data) {

    // Create a key for each "animal type" and add the animal for this key
    $result[$data][] = $animal;
}

var_dump($result)的输出是:

array (size=2)
  'mammal' => 
  array (size=2)
    0 => string 'dog' (length=3)
    1 => string 'cat' (length=3)
  'reptile' => 
  array (size=1)
    0 => string 'snake' (length=5)

所以现在,如果您想让函数执行此操作:

function getDataByKey($array) {
    $result = array();

    foreach ($array as $key => $data) {
        $result[$data][] = $key;
    }

    return $result;
}

只需执行$result = getDataByKey($array);即可得到相同的结果。