Tentang Warisan
Warisan, sering kali menjadi sebuah momok dalam kehidupan banyak masyarakat…
Misalkan kita memiliki array sebagai berikut, kemudian ingin di group dan kemudian di sort seperti command di mysql.
Array
(
[0] => Array
(
[countryid] => ID
[countryname] => Indonesia
[totalaccess] => 31
)
[1] => Array
(
[countryid] => US
[countryname] => United States
[totalaccess] => 23
)
[2] => Array
(
[countryid] => ID
[countryname] => Indonesia
[totalaccess] => 5
)
[3] => Array
(
[countryid] => ID
[countryname] => Indonesia
[totalaccess] => 2
)
[4] => Array
(
[countryid] => ID
[countryname] => Indonesia
[totalaccess] => 2
)
[5] => Array
(
[countryid] => ID
[countryname] => Indonesia
[totalaccess] => 1
)
)
di group berdasarkan countryid dan di count totalaccess nya, sehingga menjadi
Array
(
[ID] => Array
(
[countryid] => ID
[countryname] => Indonesia
[totalaccess] => 41
)
[US] => Array
(
[countryid] => US
[countryname] => United States
[totalaccess] => 23
)
)
group menggunakan fungsi sebagai berikut :
function groupArray($result, $groupkey, $countkey)
{
$finalresult = array();
foreach($result as $res)
{
$key = $res[$groupkey];
if(!isset($finalresult[$key]))
{
$finalresult[$key] = $res;
} else {
$finalresult[$key][$countkey] = $finalresult[$key][$countkey] + $res[$countkey];
}
}
return $finalresult;
}
kemudian di sort berdasarkan totalaccess
Array
(
[0] => Array
(
[countryid] => US
[countryname] => United States
[totalaccess] => 23
)
[1] => Array
(
[countryid] => ID
[countryname] => Indonesia
[totalaccess] => 41
)
)
sort menggunakan fungsi sebagai berikut :
function sortArray($a, $sortkey, $mode = "ASC")
{
foreach($a as $k=>$v)
{
$b[$k] = strtolower($v[$sortkey]);
}
if($mode == "ASC") asort($b);
else arsort($b);
foreach($b as $key=>$val)
{
$c[] = $a[$key];
}
return $c;
}
Discussion about this post