“PHP array group by key value"
$hello = array
(
array("ID" => "1","student" => "Jassi","marks" => "80","parent_id" => ""),
array("ID" => "2","student" => "Golu","marks" => "80","parent_id" => "1"),
array("ID" => "3","student" => "Jassi","marks" => "80","parent_id" => "1"),
array("ID" => "4","student" => "Jai","marks" => "90","parent_id" => "1"),
array("ID" => "5","student" => "Jassi","marks" => "85","parent_id" => "1"),
array("ID" => "6","student" => "Ravinder","marks" => "30","parent_id" => "1"),
array("ID" => "7","student" => "Mukesh","marks" => "45","parent_id" => "1"),
array("ID" => "8","student" => "Ankush","marks" => "96","parent_id" => "2"),
array("ID" => "9","student" => "Aman","marks" => "90","parent_id" => "2")
);
function group_by($key, $data) {
$result = array();
foreach($data as $val) {
if(array_key_exists($key, $val)){
$result[$val[$key]][] = $val;
}else{
$result[""][] = $val;
}
}
return $result;
}
$byGroup = group_by("student", $hello);
echo '<pre>';
print_r($byGroup);
foreach($byGroup as $sub_cate=>$subarray){
//echo $sub_cate . ' ' . $subarray;
echo 'Subarray = >' . $sub_cate . '<br>';
foreach($subarray as $print){
echo $print['ID'].',';
}
echo '<br>=========================<br>';
}
Comments
Post a Comment