0

我想知道是否有人可以帮助我。我有一个数组,我需要按“机场零售商”、“海港零售商”等进行分组。

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
....
)

结果应该是:

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

5 回答 5

2
function testFunc($array)
{
    $result = array();
    foreach($array as $_index => $_value)
    {
        $result[$_value][] = $_index;
    }
    return $result;
}
于 2013-07-05T20:59:20.877 回答
1

一种方法是循环遍历结果并为同一键添加值。这是一些虚拟代码(在这种情况下,键是值):

$data = array();
foreach ((array)$results as $item => $key) {
  $data[$key][] = $item;
}
于 2013-07-05T20:57:56.480 回答
1

您不能完全那样做,因为您会在数组中重复键(在您放置的示例中,您将有 N 个名为“[Airport Retailer]”的键。

然而,您可以创建一个数组来对您想要的项目进行分组:

$arr= array();
foreach ($initialArray as $key => $item) {
  if ($item=="[Airport Retailer]") $arr[] = $key;
}
于 2013-07-05T20:59:24.417 回答
1
function processArray( $arr ) {
  $result = Array();

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

  return $result;
}

您不能有重复的键,因此,这只是一个列表。

对于您的示例集,这将导致

Array(
  [0] => World Duty Free Group
  [1] => Duty Free Americas Inc
  [2] => DFASS Distribution
...
)
于 2013-07-05T20:59:27.430 回答
0

如果想将多个值插入同一个键,我会使用多维数组,例如:

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

老实说,我希望这会有所帮助,我会这样做。

于 2015-04-23T13:58:58.520 回答