简体   繁体   中英

sort this array from highest to lowest

so i make an apriori algorithm, and this is the result.

阵列图片

this is the code where i get this array from.

$count = array_count_values($arrayCount);

$array = [];

foreach($count as $key => $value){
    $confidence = ($value/$count_antecedent);
    $support = ($value/$count_all_transactions);
   
    $isi = [
        $key=>$confidence*$support
    ];
    array_push($array,$isi);
}



return $array;

i want to sort it from highest to lowest but also keeping the key.

if this array is sorted all i need is to take 4 highest number.

it will look like this (if sorted):

  $i = 0;
 foreach($sortedArray as $key => $value){
    if($i == 0){
     $product1 == product::find($key);
    }
    else if($i == 1){
     $product2 = product::find($key);
    }
    else if($i == 2){
    $product3 = product::find($key);
    }
   else if($i == 3){
    $product4 = product::find($key);
   }
   $i++;
 }

use arsort($array) function.

It's all you need.

so in order to order the array i need to use usort where the key name should be the same in every array.

so i changed the $isi variable to

$isi = ["value"=>$confidence*$support,"key"=>$key];

and then use this usort function to order the array

usort($array,function($a,$b){
 return $a["value"] < $b["value"];
})

and then to get 4 highest product from db there slighly change to the code

  $i = 0;
 foreach($array as $key => $value){
    if($i == 0){
     $product1 = product::find($value['key']);
    }
    else if($i == 1){
     $product2 = product::find($value['key']);
    }
    else if($i == 2){
    $product3 = product::find($value['key']);
    }
   else if($i == 3){
    $product4 = product::find($value['key']);
   }
   $i++;
 }

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