Jump to content

Non random array sort?


originalucifer

Recommended Posts

My brain hurts. I've been trying to sort a result set in a specific way. I'll simplify the structure to make it easy. [ROWID] [sORTID] [iP_ADDRESS]. lets say i've got 15 rows, 5 of each have the same [iP_ADDRESS]. I Want to reorder the result set (Array) so that no 2 [iP_ADDRESS] are in order.

 

so currently:      rowid    sortid  address

                          1          10    192.168.0.1

                          2          20    192.168.0.1

                          3          30    192.168.0.2

want:

                          1          10    192.168.0.1

                          3          30    192.168.0.2

                          2          20    192.168.0.1

 

I will then reset the sortid, and reinsert into the db. This sorting issue is driving me nuts! help!

 

Link to comment
https://forums.phpfreaks.com/topic/109055-non-random-array-sort/
Share on other sites

my stab at it

<?php 

$arr = array ( 	0  => 'B', 
			1  => 'B', 
			2  => 'A', 
			3  => 'A', 
			4  => 'A', 
			5  => 'A', 
			6  => 'A', 
			7  => 'C', 
			8  => 'C', 
			9  => 'C', 
			10 => 'C', 
			11 => 'C', 
			12 => 'C', 
			13 => 'D', 
			14 => 'E' );

$karr = array_count_values($arr);                       // get counts of he values
$max = max($karr);                                      // get highest count
arsort($karr);                                          // sort in desc count order
foreach ($karr as $k => $v)
for ($i=0; $i<$v; $i++)
	$barr[] = $k;                                   // put in array ordered by count CCCCCCAAAAABBDE
$chunks = array_chunk($barr, $max);                     // chunk the array - chunk size = max count CCCCCC AAAAAB BDE
for ($i=0; $i<$max; $i++)
foreach ($chunks as $c)
	if ($c[$i]) $result[] = $c[$i];                 // cycle through the chunks adding next element each time
echo '<pre>', print_r($result, true), '</pre>';
?>

-->
Array
(
    [0] => C
    [1] => A
    [2] => B
    [3] => C
    [4] => A
    [5] => E
    [6] => C
    [7] => A
    [8] => D
    [9] => C
    [10] => A
    [11] => C
    [12] => A
    [13] => C
    [14] => B
)

After this code

<?php
$karr = array_count_values($arr);                       // get counts of the values
$max = max($karr);                                      // get highest count
arsort($karr);                                          // sort in desc count order
echo '<pre>', print_r($karr, true), '</pre>';

 

$karr contains

Array
(
    [C] => 6
    [A] => 5
    [b] => 2
    [E] => 1
    [D] => 1
)

so $v is count of each item $k.

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.