排序数组PHP usort

时间:2016-03-08 09:54:58

标签: php arrays usort

我正在尝试按$ weekrent排序我的数组输出,到目前为止我已经得到了这个但是我得到的输出是重复的相同数据而不是它的命令。有没有其他方法可以让我这样做,所以我可以根据变量排序数据?

    $values = $client->SearchProperties($parameters);

if(!is_array($values->SearchPropertiesResult->PropertyInfo))
{
    $values->SearchPropertiesResult->PropertyInfo = array($values->SearchPropertiesResult->PropertyInfo);
}

if($values != '')
{
    $arrayForSort = array();
    foreach ($values->SearchPropertiesResult->PropertyInfo as $message)
    {
        $uglyid = $message->ID;
        $id = $message->FriendlyID;
        $mainphoto = $message->MainPhoto->PhotoUrl;
        $furnished = $message->Furnished;
        $addressline1 = $message->Address1;
        $rooms = $message->MaxTenants;
        $rent = $message->Rent;
        $description = $message->Description;
        $isletagreed = $message->IsLetAgreed;
        $facilities = $message->Facilities->FacilityInfo;
        $photos = $message->Photos->PhotoInfo;
        $roomsinfo = $message->Rooms->RoomInfo;
        $facilitiesstring = serialize($facilities);
        $extractnumbers = ereg_replace("[^0-9]", "", $rent);
        $monthrent = ($extractnumbers) / $rooms;
        $monthrentrounded = number_format(($monthrent/100),2);
        $weekrent = ($monthrentrounded) * 12 / 52;
        $arrayForSort[] = array('weekrent' => $weekrent, 'message' => $message);
        $weekrentrounded = floor($weekrent * 100) / 100;

        $roomsinfojson = json_encode($roomsinfo);
        $facilitiesjson = json_encode($facilities);
        $roomsinfodouble = (substr_count(strip_tags($roomsinfojson),"Double"));
        $roomsinfosingle = (substr_count(strip_tags($roomsinfojson),"Single"));
        $roomsinfobathroom = (substr_count(strip_tags($roomsinfojson),"Bathroom"));
        $roomsinfoshower = (substr_count(strip_tags($roomsinfojson),"Shower"));
        $facilitiesparking = (substr_count(strip_tags($facilitiesjson),"Parking"));
        $facilitiesgarden = (substr_count(strip_tags($facilitiesjson),"Garden"));

        $totalbathrooms = $roomsinfobathroom + $roomsinfoshower;
        $totalimages = count($photos);
                }

        foreach ($arrayForSort as $item)
        {
             usort($arrayForSort, function($a, $b) {
            return $a['weekrent'] - $b['weekrent'];
        });
             $message = $item['message'];
        echo '$addressline1';
    }
}

任何帮助都会很棒!

1 个答案:

答案 0 :(得分:1)

如果你的数组包含key / index,那么你可以使用uasort()php函数。

$sort = uasort($arrayForSort, function($a, $b)
        {
            return $b['weekrent'] - $a['weekrent'];
        }
);

如果要对多个元素进行排序,则可以使用以下代码:

$sort = uasort($arrayForSort, function($a, $b)
        {
            $c = $b['weekrent'] - $a['weekrent'];
            $c .= $b['id'] - $a['id'];
            return $c;
        }
);

然后你必须打印arrayForSort,你会得到结果。

printr($arrayForSort);