Jump to content

Array Sort


tobeyt23

Recommended Posts

I have an array like such and i want to change the sort so the shortnames per titlename are in a set order this is what I have and it's not working, any suggestions?

<?php
$array = array(
  array(
		'orderId'=>'269',
		'titleName' => '1984',
		'shortName'=>'CYO'
		),
  array(
		'orderId'=>'269',
		'titleName' => '1984',
		'shortName'=>'Litplan'
		),
  array(
		'orderId'=>'269',
		'titleName' => '1984',
		'shortName'=>'Puzzle Pack'
		),
  array(
		'orderId'=>'269',
		'titleName' => 'And Then There Were None',
		'shortName'=>'CYO'
		),
  array(
		'orderId'=>'269',
		'titleName' => 'And Then There Were None',
		'shortName'=>'Litplan'
		),
  array(
		'orderId'=>'269',
		'titleName' => 'And Then There Were None',
		'shortName'=>'Puzzle Pack'
		),
  );

function array_sort($a)
{
$count=0;
switch($a['shortName']) {
	case 'LitPlan Teacher Pack':
		$count++;
		return ($count == 0) ? 0 : $count;
		break;
	case 'Puzzle Pack':
		$count++;
		return ($count == 0) ? 0 : $count;
		break;
	case 'CYO':
		$count++;
		return ($count == 0) ? 0 : $count;
		break;
	case 'Dual Language':
		$count++;
		return ($count == 0) ? 0 : $count;
		break;
	case 'DramaWorks Guide':
		$count++;
		return ($count == 0) ? 0 : $count;
		break;
}
}
usort($array, "array_sort");
?>

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

try this

function msort($array, $id="id") {
        $temp_array = array();
        while(count($array)>0) {
            $lowest_id = 0;
            $index=0;
            foreach ($array as $item) {
                if (isset($item[$id]) && $array[$lowest_id][$id]) {
                    if (strtolower($item[$id])<strtolower($array[$lowest_id][$id])) {
                        $lowest_id = $index;
                    }
                }
                $index++;
            }
            $temp_array[] = $array[$lowest_id];
            $array = array_merge(array_slice($array, 0,$lowest_id), array_slice($array, $lowest_id+1));
        }
        return $temp_array;
    }

then you just call it like this

$array=msort($array,"shortName"); 

Link to comment
https://forums.phpfreaks.com/topic/152255-array-sort/#findComment-800370
Share on other sites

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.