Jump to content

[SOLVED] Array Sorts issues


cooldude832

Recommended Posts

I have an array populated by

<?php
while($row = fetch){
				$test = $row['Hits']*$row['Deals']*$row['Rating'];
				$data[$i]['Name'] = $row['Username'];
				$data[$i]['id'] = $row['UserID'];
				$data[$i]['Score'] = $test;
}
?>

it looks like

 

Array

(

    [0] => Array

        (

            [Name] => cooldude_832

            [id] => 1

            [score] => 188.628

        )

 

    [1] => Array

        (

            [Name] => TheDealerUK

            [id] => 2

            [score] => -669.3

        )

 

)

 

I want to sort the array by the $data[]['Score'] field any ideas?

I tried making the scores the keys and then using a ksort, but I want to destroy the keys and have it renumber them

so any ideas?

Link to comment
https://forums.phpfreaks.com/topic/84585-solved-array-sorts-issues/
Share on other sites

When you take a computer science class, one of the very first things they (should) teach you is how to implement a quicksort. For this, you'll need to write your own sort implementation - a quicksort is a good start.

 

Note that quicksort isn't very efficient, relative to other methods of sorting, but it's a good place to get started. If you want to, you can research other sorting algorithms.

usort()

 

<?php
$data = array
(
   

    array

        (
            'Name' => 'cooldude_832',
            'id' => 1,
            'Score' => 188.628
        ),

    array
        (
            'Name' => 'TheDealerUK',
            'id' => 2,
            'Score' => -669.3
        )

);

function scoresort($a, $b)
{
    return $a['score'] - $b['score'];
}

usort ($data , 'scoresort');

echo '<pre>', print_r($data, true), '</pre>';
?>

I tried your function (which didn't make sense to me)

doing

<?php
			function scoresort($a, $b){
				return $a['score'] - $b['score'];
				}
			print_r($data);
			usort ($data , 'scoresort');
			print_r($data);
?>

then it returns

Array

(

    [0] => Array

        (

            [Name] => cooldude_832

            [id] => 1

            [score] => 62.37

        )

 

    [1] => Array

        (

            [Name] => TheDealerUK

            [id] => 2

            [score] => 41.44

        )

 

)

Array

(

    [0] => Array

        (

            [Name] => TheDealerUK

            [id] => 2

            [score] => 41.44

        )

 

    [1] => Array

        (

            [Name] => cooldude_832

            [id] => 1

            [score] => 62.37

        )

 

)

 

 

as you can see it is going backwards of what I wanted

 

I'll just rsort it from there and be set?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.