使用arsort对二维数组进行排序

时间:2014-07-15 10:34:29

标签: php arrays

这是我的数组prob,其中包含两个值value(int)和tag(字符串)。

在循环结束时,我希望按value对数组进行排序,并希望使用tag打印前5个值。

        foreach($POS as $p)
        {
            //echo "POS  :".$p."<br/>";
            while ($row1 = @mysqli_fetch_array($selectTag))
            {
                //Calculate total pos for given tag
                //echo "Tag : ".$row1['tag']."<br/>";
                $selectPOS1 = mysqli_query($con,"SELECT * from koove_posts where tag = '".$row1['tag']."'");
                while ($row2 = @mysqli_fetch_array($selectPOS1))
                {
                    //echo $row2['pos']."<br/>";
                    $totalPOSs.=$row2['pos'].",";       
                }
                $totalPOS_count = str_word_count($totalPOSs);

                //calculate how many times particular 'pos' appears for given tag
                $pos_Count = substr_count($totalPOSs, $p);

                //Calculate the probability for each part of speach
                $prob[] = (object) array(
                    "value" => ($pos_Count + 1)/ ($totalPOS_count + $distinct_pos_Count),
                    "tag"   => $row1['tag'],
                    );
                    }               
        }

        arsort($prob);
        $prob = array_slice($prob, 0, 5);
        foreach ($prob as $array)
        {
            echo "Tag :". $array->tag." Probablity :".$array->value."<br/>";
        }

我尝试了这个,但它从列表中打印出前5个标签。

1 个答案:

答案 0 :(得分:0)

您应该以这种方式使用uasort功能:

<?php

$prob = [];

$prob[] = (object) array('value' => 1, 'tag' => 2);
$prob[] = (object) array('value' => 2, 'tag' => 4);
$prob[] = (object) array('value' => 3, 'tag' => 6);
$prob[] = (object) array('value' => 4, 'tag' => 8);
$prob[] = (object) array('value' => 5, 'tag' => 10);
$prob[] = (object) array('value' => 6, 'tag' => 12);

var_dump($prob);


uasort ($prob, function($a, $b) {

if ($a->value == $b->value) {
        return 0;
    }
    return ($a->value < $b->value) ? 1 : -1;    

});


var_dump($prob);