0

How to sort an array without replacing index element? When I descending order sort an absent array then indexing value will be replace, is there any way to descending order sort an array and keep original indexes?

// Get Current Session
$Res_Sess = mysql_query("SELECT sessionid from tbl_session WHERE status=1 ORDER BY sessionid desc limit 1");
$Row_Sess = mysql_fetch_array($Res_Sess);
$Session = $Row_Sess[0];

// Get Batch
$Res_Bat = mysql_query("SELECT batchid,batchname,code FROM tbl_batch where status=1 and batchid!=12 ORDER BY batchid asc");
$allAbsent = array();
$indexes = 0;

while ($Row_Bat = mysql_fetch_array($Res_Bat)) {
    $Batch = $Row_Bat['batchid'];
    $Bat_Code = $Row_Bat['code'];
    $qatt1 = mysql_query("select count(id),rollno from tbl_attendance where batchid = '$Batch' and sessionid = '$Session' GROUP BY rollno");
    $array = array();
    $array_rollno = array();
    $i1 = 0;
    while ($Row_T = mysql_fetch_array($qatt1)) {
        $array[$i1] = $Row_T[0];
        $array_rollno[$i1] = $Row_T[1];
        $i1++;
    }

    $maxValue = max($array);
    $roll_no = $array_rollno;
    foreach($roll_no as $roll) {
        $allRollno[$indexes] = $roll;

        // Absent - Attendance
        $Abatt4 = mysql_query("select count(id) from tbl_attendance where rollno = '$roll' and batchid = '$Batch' and sessionid = '$Session' and attend = 0 GROUP by rollno");

        if ($Row_A4 = mysql_fetch_array($Abatt4)) {
            $allAbsent[$indexes] = round(($Row_A4[0] / $maxValue * 100) , 2);
        } else {
            $allAbsent[$indexes] = 0;
        }

        $indexes++;
    }

    print_r($allAbsent);
    echo "<br /><br />";
    $tabsent = $allAbsent;
    rsort($tabsent);
    foreach($tabsent as $key => $val) {
        echo "[$key] => $val\n";
    }
2
  • All of the PHP array sorting functions will reassign the indexes after sorting. Why not sort in you SQL query instead? That should order the data before you even assign it to an array. Commented Feb 21, 2019 at 11:35
  • Could you please post your sorted data in ques. Actaully i want to know which type of array you are using . Is it assocative array? Commented Feb 21, 2019 at 11:45

1 Answer 1

2

A quick Google search normally does the trick...

arsort($tabsent);

From the manual:

arsort — Sort an array in reverse order and maintain index association

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.