George Feichter
George Feichter

Reputation: 69

Flip an associative array containing duplicate values without losing elements

I wonder if someone can help me. I have an array which I need to group by 'Airport Retailer', 'Seaport Retailer', etc.

Array
(
    [World Duty Free Group] => Airport Retailer
    [Duty Free Americas Inc] => Airport Retailer
    [DFASS Distribution] => Airport Retailer
    [Monalisa Int'l SA] => Downtown Retailer
    [DUFRY America 1] => Seaport Retailer
    [Neutral Duty Free Shop] => Border Retailer
    [Saint Honoré] => 
    [SMT PR Duty Free Inc] => Seaport Retailer
    [Aer Rianta International] => Airport Retailer
    [London Supply] => Downtown Retailer
    [Royal Shop Duty Free] => Downtown Retailer
    [Harding Brothers Retail] => Cruise/Ferry Retailers
    [Motta Internacional SA] => Airport Retailer
    [Tortuga Rum Co Ltd] => Downtown Retailer
    [Pama Duty Free] => Seaport Retailer
    [Little Switzerland] => Downtown Retailer
....
)

The result should be:

Array
(
    [Airport Retailer] => World Duty Free Group
    [Airport Retailer] => Duty Free Americas Inc
    [Airport Retailer] => DFASS Distribution
...
)

Upvotes: 0

Views: 83

Answers (5)

Giovanni Di Toro
Giovanni Di Toro

Reputation: 809

I'd use a multi-dimensional array if ever wanted to insert multiple values into a same key, such as:

Array(
  [Airport Retailer] => array (World Duty Free Group,
                               Duty Free Americas Inc,
                               DFASS Distribution),
  [foo] => x,
  [bar] => array(y,w,z)
)

I honestly hope that helps, I'd do it like that.

Upvotes: 0

Sumurai8
Sumurai8

Reputation: 20737

function processArray( $arr ) {
  $result = Array();

  foreach( $arr as $key => $val ) {
    if( $val === "Airport Retailer" ) {
      $result[] = $key;
    }
  }

  return $result;
}

You cannot have duplicate keys, therefore, this is 'just' a list.

For your example set this will result in

Array(
  [0] => World Duty Free Group
  [1] => Duty Free Americas Inc
  [2] => DFASS Distribution
...
)

Upvotes: 1

Racso
Racso

Reputation: 2449

You can't do it exactly that way, as you would repeat keys in the array (in the example you put, you would have N keys named "[Airport Retailer]".

Yet, you can create an array grouping the items you want:

$arr= array();
foreach ($initialArray as $key => $item) {
  if ($item=="[Airport Retailer]") $arr[] = $key;
}

Upvotes: 1

user576126
user576126

Reputation:

function testFunc($array)
{
    $result = array();
    foreach($array as $_index => $_value)
    {
        $result[$_value][] = $_index;
    }
    return $result;
}

Upvotes: 2

n2o
n2o

Reputation: 41

One way to do this by looping over your results and add values for the same key. Here is some dummy-code (in this case the key is the value):

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

Upvotes: 1

Related Questions