我使用了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