分组关联数组

I want to be able to group Associative Arrays with their `keys. So far I'm lost of what syntax to use.

As of now, I have thus code,

$associativeArray = array("Ripe Mango"=>"Yellow", "Strawberry"=>"Red", "Lemon"=>"Yellow");
groupByColor($associativeArray);

function groupByColor($groupedArray)
{
  return $groupedArray;
}

My goal is to return the array while having it grouped, the ideal result will be like this;

["Yellow"=>["Ripe Mango", "Lemon"], "Red"=>["Strawberry"]]

Any hints on what method to use?

Inside function do foreach()

<?php

$associativeArray = array("Ripe Mango"=>"Yellow", "Strawberry"=>"Red", "Lemon"=>"Yellow");

function groupByColor($associativeArray){
    $final_array = [];
    foreach($associativeArray as $key=>$val){
        $final_array[$val][] = $key;
    }

   return $final_array;  
}
print_r(groupByColor($associativeArray));

Output:- https://eval.in/933011

Note:- you can assign groupByColor($associativeArray) returned array to a new variable and print that variable like below:-

$color_array = groupByColor($associativeArray);
print_r($color_array);

You can do this by processing each key and convert value to key and check if exist then append to it else create it

function groupByColor ($groupedArray) {
  $result = array();
  foreach ($groupedArray as $key=>$val) {
    if (array_key_exists($val, $result)) {
      $result[$val][] = $key;
    } else {
      $result[$val] = array();
    }
  }
  return $result;
}

foreach() through your array and add to a new array with the color as key:

<?php
$associativeArray = array("Ripe Mango"=>"Yellow", "Strawberry"=>"Red", "Lemon"=>"Yellow");
$new = groupByColor($associativeArray);
var_dump($new);

function groupByColor($groupedArray)
{
    foreach ( $groupedArray as $key => $color ) {
        $tmp[$color][] = $key;
    }
    return $tmp;
}

You can use array_walk function to trait every value of the array:

<?php
$array = ["Ripe Mango"=>"Yellow", "Strawberry"=>"Red", "Lemon"=>"Yellow"];
$result = [];
array_walk($array, function ($value, $key) use (&$result) {
    $result[$value][] = $key;
});

print_r($result);

Only way I know how to do it would be with a loop.

<!DOCTYPE html>
<html>
<body>

<?php
$associativeArray = array("Ripe Mango"=>"Yellow", "Strawberry"=>"Red", "Lemon"=>"Yellow");

$data = groupByColor($associativeArray);
print_r($data);

function groupByColor($groupedArray)
{
    foreach ($groupedArray as $key => $value) {
        $final[$value][] = $key;
     } 

    return $final;
}
?>

</body>
</html>