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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.