在PHP中,我有一个名为$ listing的二维数组,它将包含具有以下结构的数据:
(
[1] => Array
(
[category] => tech
[business_name] => Apple
)
[2] => Array
(
[category] => food
[business_name] => McDonalds
)
[3] => Array
(
[category] => tech
[business_name] => Dell
)
)
我希望以 category (按字母顺序排列),然后* business_name *(按字母顺序排序)分组的纯文本输出。请注意,这只是其显示方式的一个子集 - 可能有50个类别和1000个列表 - 因此代码需要考虑到这一点。
因此,如上所述使用$ listing的输出,我需要输出如下所示:
category: food
business_name: McDonalds
category: tech
business_name: Apple
business_name: Dell
请帮助。提前谢谢。
答案 0 :(得分:2)
有很多方法可以做到这一点,但这应该让你开始。
$data = array();
foreach ($listing as $item) {
$data[$item['category']][] = $item['business_name'];
}
ksort($data);
$data = array_map(function($names) {
sort($names);
return $names;
}, $data);
未经测试...
答案 1 :(得分:0)
看看PHP多阵列排序 http://www.php.net/manual/en/function.array-multisort.php对您的数组进行多重排序,看看是否有帮助
答案 2 :(得分:0)
我用array_multisort() 功能。请看下面的代码。
<?php
//array to sort
$data[0] = array('category'=> 'tech','business_name' => 'apple') ;
$data[1] = array('category'=> 'food','business_name' => 'McDonalds') ;
$data[2] = array('category'=> 'tech','business_name' => 'dell') ;
$data[3] = array('category'=> 'food','business_name' => 'subway') ;
foreach($data as $key => $val){
$cat[$key] = $val['category'];
$bus[$key] = $val['business_name'];
}
// Sort the data with category and business_name with ascending order
array_multisort($cat, SORT_ASC, $bus, SORT_ASC, $data);
// echo "<pre>";print_r($data);echo "</pre>";unset($val);
//put the category as key And business name as value with comma seperated.
$category = array();
foreach($data as $key => $val){
if(array_key_exists($val['category'],$category ))
{
$category[$val['category']] = $category[$val['category']].', '.$val['business_name'];
}
else
{
$category[$val['category']] = $val['business_name']; // $category
}
}
//print the sorted data
foreach($category as $key => $val){
//print category
echo "<br /> <br />Category: ".$key;
$b_name = explode(',', $val);
//to print busniess name
foreach($b_name as $k => $v){
echo "<br />Business Name: ".$v;
}
}
?>
//OUTPUT
Category: food
Business Name: McDonalds
Business Name: subway
Category: tech
Business Name: apple
Business Name: dell