我想知道是否有人可以帮助我。我有一个数组,需要按“机场零售商”、“海港零售商”等进行分组。
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
...
)
function testFunc($array)
{
$result = array();
foreach($array as $_index => $_value)
{
$result[$_value][] = $_index;
}
return $result;
}
实现此目的的一种方法是循环结果并为同一键添加值。 这是一些虚拟代码(在这种情况下,键就是值):
$data = array();
foreach ((array)$results as $item => $key) {
$data[$key][] = $item;
}
你不能完全那样做,因为你会重复数组中的键(在你放置的示例中,你将有 N 个名为“[Airport Retailer]”的键。
但是,您可以创建一个数组来对所需的项目进行分组:
$arr= array();
foreach ($initialArray as $key => $item) {
if ($item=="[Airport Retailer]") $arr[] = $key;
}
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
...
)
如果想要将多个值插入到同一个键中,我会使用多维数组,例如:
Array(
[Airport Retailer] => array (World Duty Free Group,
Duty Free Americas Inc,
DFASS Distribution),
[foo] => x,
[bar] => array(y,w,z)
)
老实说,我希望这有帮助,我会这样做。