Skip to main content

How to get PHP array group by key value?

“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

Popular posts from this blog

How to check date format in PHP?

Check date format in PHP function isCorrectDateFromat($date){     if(!empty($date)){         $dateString = $date; // Replace this with your date string         $format = "Y-m-d"; // Replace this with your expected date format         $dateTime = DateTime::createFromFormat($format, $dateString);         if ($dateTime === false) { /*             echo "The date is not in the correct format."; */         } else {             $errors = DateTime::getLastErrors();             if (empty($errors)) { /*                 echo "The date is in the correct format."; */                 return true;             } else { /*                 echo "...