简体   繁体   中英

How to add a “sort by” field to mysqli array in php code and then sort by it descending?

I have the results of a mysql query, I'd like to add a new field and populate with a calculated value that I'd like to then sort by, I'm new with adding fields to arrays and sorting of arrays so any help is appreciated, thanks.

$keyArray = explode(" ", $keyPhrase);
$result = $mysqli->query($queryString);
while($row = $result->fetch_array()){
    $rows[] = $row;
}            
foreach($rows as $row){
    $bodyData = $row["bodydata"];
    $totalKeys = 0;
    foreach($keyArray as $value){
        $keyCount = substr_count($bodyData, $value);
        $totalKeys = $totalKeys + $keyCount;
                }
        // Here I'd like to add new field to $rows[] 
        // with $totalKeys value then sort by it desc after the this loop
     }
}

I got it to work like this:

foreach($rows as &$row){
        $bodyData = $row["bodydata"];
        $totalKeys = 0;
        foreach($keyArray as $value){
            $keyCount = substr_count($bodyData, $value);
            $totalKeys = $totalKeys + $keyCount;
        }                
        $row["sortcount"] = $totalKeys;                 
    }
    $rows = array_sort($rows, "sortcount", SORT_DESC);


function array_sort($array, $on, $order=SORT_ASC)
{
$new_array = array();
$sortable_array = array();

if (count($array) > 0) {
    foreach ($array as $k => $v) {
        if (is_array($v)) {
            foreach ($v as $k2 => $v2) {
                if ($k2 == $on) {
                    $sortable_array[$k] = $v2;
                }
            }
        } else {
            $sortable_array[$k] = $v;
        }
    }

    switch ($order) {
        case SORT_ASC:
            asort($sortable_array);
        break;
        case SORT_DESC:
            arsort($sortable_array);
        break;
    }

    foreach ($sortable_array as $k => $v) {
        $new_array[$k] = $array[$k];
    }
}

return $new_array;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM