-2

I want to combine all the keys for a same values and make the value as key

Sample data:

Array
(
    [825] => ca_knife_features 
    [838] => ca_knife_features 
    [795] => ca_knife_handle_materials 
    [853] => ca_knife_handle_materials 
)

Desired result:

Array
(
[ca_knife_features]=>array(825,838)
[ca_knife_handle_materials]=>array(795,853)
)

How can I do this?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Rohit Goel
  • 3,396
  • 8
  • 56
  • 107
  • 2
    Did you try a foreach loop or something equal already? – RST Apr 24 '17 at 17:50
  • 2
    You are expected to try to **write the code yourself**. After [**doing more research**](https://meta.stackoverflow.com/q/261592/1011527) if you have a problem **post what you've tried** with a **clear explanation of what isn't working** and provide [a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). Read [How to Ask](http://stackoverflow.com/help/how-to-ask) a good question. Be sure to [take the tour](http://stackoverflow.com/tour) and read [this](https://meta.stackoverflow.com/q/347937/1011527). – Jay Blanchard Apr 24 '17 at 17:51
  • 1
    a very simple foreach loop can solve this. Is this a project for a class or something? – Forbs Apr 24 '17 at 17:53

2 Answers2

1

Getting all the keys for all the values is easy.

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

But that doesn't get only the duplicate values. There are different ways to do that. One way is by filtering the result to only show values with more than one key.

$result = array_filter($result, function($item) {
    return count($item) > 1;
});
Don't Panic
  • 41,125
  • 10
  • 61
  • 80
-1

I have done it with the below code:

foreach($multiattrData as $key=>$value)
    if(array_key_exists($value, $out)){
    $out[$value][] = $key;}
    else{
         $out[$value] = array($key);  
    }
halfer
  • 19,824
  • 17
  • 99
  • 186
Rohit Goel
  • 3,396
  • 8
  • 56
  • 107