RE: [PHP] Sorting Help

2012-04-11 Thread admin
-Original Message-
From: Floyd Resler [mailto:fres...@adex-intl.com] 
Sent: Wednesday, April 11, 2012 11:26 AM
To: PHP
Subject: [PHP] Sorting Help

I need to sort the following array:
{
[Smith, Bob]=array(137.5,125.5),
[Jones, Robert]=array(132.7,128.2)
}

The array needs to be sorted by the first number (i.e. 137.5) and then the
second in descending order.  I looked at array_multisort but couldn't figure
out how to make work for my needs.

Thanks!
Floyd


Do me a favor and copy a print_r of your array because this I can't figure
out what you're are doing with that.






-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] Sorting Help

2012-04-11 Thread admin


-Original Message-
From: Floyd Resler [mailto:fres...@adex-intl.com] 
Sent: Wednesday, April 11, 2012 11:26 AM
To: PHP
Subject: [PHP] Sorting Help

I need to sort the following array:
{
[Smith, Bob]=array(137.5,125.5),
[Jones, Robert]=array(132.7,128.2)
}

The array needs to be sorted by the first number (i.e. 137.5) and then the
second in descending order.  I looked at array_multisort but couldn't figure
out how to make work for my needs.

Thanks!
Floyd



Here is what I did to your array

$test = array(Smith, Bob=array(137.5,125.5),Jones
Robert=array(132.7,128.2));
asort($test);
print_r('pre');
print_r($test);






-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting Help

2012-04-11 Thread Floyd Resler

On Apr 11, 2012, at 1:11 PM, admin wrote:

 
 
 -Original Message-
 From: Floyd Resler [mailto:fres...@adex-intl.com] 
 Sent: Wednesday, April 11, 2012 11:26 AM
 To: PHP
 Subject: [PHP] Sorting Help
 
 I need to sort the following array:
 {
   [Smith, Bob]=array(137.5,125.5),
   [Jones, Robert]=array(132.7,128.2)
 }
 
 The array needs to be sorted by the first number (i.e. 137.5) and then the
 second in descending order.  I looked at array_multisort but couldn't figure
 out how to make work for my needs.
 
 Thanks!
 Floyd
 
 
 
 Here is what I did to your array
 
 $test = array(Smith, Bob=array(137.5,125.5),Jones
 Robert=array(132.7,128.2));
 asort($test);
 print_r('pre');
 print_r($test);
 
 

That almost worked. I did an arsort() and got the following:
Array
(
[Guy, Matt] = Array
(
[0] = 164.67
[1] = 135.67
)

[Smith, Toby] = Array
(
[0] = 159.33
[1] = 132.33
)

[Young, Matt] = Array
(
[0] = 157.67
[1] = 131.67
)

[Shobe, Dale ] = Array
(
[0] = 157.67
[1] = 128.67
)

[King, Derrick] = Array
(
[0] = 155.67
[1] = 126.67
)

[Reynolds, Jeff] = Array
(
[0] = 155.67
[1] = 133.67
)

[Bobo, Tom] = Array
(
[0] = 152.33
[1] = 124.33
)

[Henderson, Cody] = Array
(
[0] = 150.33
[1] = 121.33
)

[McGuffin, Jimmy] = Array
(
[0] = 145.67
[1] = 118.67
)

[Stone, Richard] = Array
(
[0] = 145
[1] = 119.00
)

[Biggerstaff, David ] = Array
(
[0] = 142.33
[1] = 115.33
)

[Dennis, Daymon] = Array
(
[0] = 142
[1] = 114.00
)

[Bush, Duke] = Array
(
[0] = 141
[1] = 121.00
)
}

That's not the entire array but it sorts just fine except for two entries.  For 
some reason these two aren't sorting in descending order of the second element:
[King, Derrick] = Array
(
[0] = 155.67
[1] = 126.67
)

[Reynolds, Jeff] = Array
(
[0] = 155.67
[1] = 133.67
)
Everything else sorts just fine.  I'm not sure why that is.

Thanks!
Floyd



Re: [PHP] Sorting Help

2012-04-11 Thread Stuart Dallas
On 11 Apr 2012, at 16:26, Floyd Resler wrote:

 I need to sort the following array:
 {
   [Smith, Bob]=array(137.5,125.5),
   [Jones, Robert]=array(132.7,128.2)
 }
 
 The array needs to be sorted by the first number (i.e. 137.5) and then the 
 second in descending order.  I looked at array_multisort but couldn't figure 
 out how to make work for my needs.

Use a custom sorting function, then you can sort any way you want: 
http://php.net/usort

-Stuart

-- 
Stuart Dallas
3ft9 Ltd
http://3ft9.com/
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting Help

2012-04-11 Thread Bastien


Bastien Koert

On 2012-04-11, at 2:18 PM, Floyd Resler fres...@adex-intl.com wrote:

 
 On Apr 11, 2012, at 1:11 PM, admin wrote:
 
 
 
 -Original Message-
 From: Floyd Resler [mailto:fres...@adex-intl.com] 
 Sent: Wednesday, April 11, 2012 11:26 AM
 To: PHP
 Subject: [PHP] Sorting Help
 
 I need to sort the following array:
 {
[Smith, Bob]=array(137.5,125.5),
[Jones, Robert]=array(132.7,128.2)
 }
 
 The array needs to be sorted by the first number (i.e. 137.5) and then the
 second in descending order.  I looked at array_multisort but couldn't figure
 out how to make work for my needs.
 
 Thanks!
 Floyd
 
 
 
 Here is what I did to your array
 
 $test = array(Smith, Bob=array(137.5,125.5),Jones
 Robert=array(132.7,128.2));
 asort($test);
 print_r('pre');
 print_r($test);
 
 
 
 That almost worked. I did an arsort() and got the following:
 Array
 (
[Guy, Matt] = Array
(
[0] = 164.67
[1] = 135.67
)
 
[Smith, Toby] = Array
(
[0] = 159.33
[1] = 132.33
)
 
[Young, Matt] = Array
(
[0] = 157.67
[1] = 131.67
)
 
[Shobe, Dale ] = Array
(
[0] = 157.67
[1] = 128.67
)
 
[King, Derrick] = Array
(
[0] = 155.67
[1] = 126.67
)
 
[Reynolds, Jeff] = Array
(
[0] = 155.67
[1] = 133.67
)
 
[Bobo, Tom] = Array
(
[0] = 152.33
[1] = 124.33
)
 
[Henderson, Cody] = Array
(
[0] = 150.33
[1] = 121.33
)
 
[McGuffin, Jimmy] = Array
(
[0] = 145.67
[1] = 118.67
)
 
[Stone, Richard] = Array
(
[0] = 145
[1] = 119.00
)
 
[Biggerstaff, David ] = Array
(
[0] = 142.33
[1] = 115.33
)
 
[Dennis, Daymon] = Array
(
[0] = 142
[1] = 114.00
)
 
[Bush, Duke] = Array
(
[0] = 141
[1] = 121.00
)
 }
 
 That's not the entire array but it sorts just fine except for two entries.  
 For some reason these two aren't sorting in descending order of the second 
 element:
 [King, Derrick] = Array
(
[0] = 155.67
[1] = 126.67
)
 
[Reynolds, Jeff] = Array
(
[0] = 155.67
[1] = 133.67
)
 Everything else sorts just fine.  I'm not sure why that is.
 
 Thanks!
 Floyd
 

Check that you don't have a space in front of those values. That could cause 
some confusion. 
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting an array

2011-03-01 Thread Jim Lucas
On 2/28/2011 7:52 PM, Ron Piggott wrote:
 
 I need help to know how to sort the words / phrases in my array.
 
 Variable name: $words_used
 print_r( $words_used ); Current output: Array ( [187] = Sin [249] = 
 Punished [98] = Sanctuary [596] = Sing [362] = Anointing Oil )
 Desired result: Alphabetical sort: Array ( [362] = Anointing Oil [249] = 
 Punished [98] = Sanctuary [187] = Sin [596] = Sing ) 
 
 The #’s are the auto_increment value of the word in the mySQL database.  The 
 number is not representative of alphabetical order, but the order it was 
 added to the database.
 
 Thank you for your assistance.
 
 Ron
 
 The Verse of the Day
 “Encouragement from God’s Word”
 http://www.TheVerseOfTheDay.info  
 

Besides the answer others have pointed you to, I would recommend doing it in 
mysql?

SELECT * FROM table ORDER BY your_column;

Check out the syntax for it here.

http://dev.mysql.com/doc/refman/5.0/en/select.html
and
http://dev.mysql.com/doc/refman/5.0/en/order-by-optimization.html

Jim Lucas

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting an array

2011-02-28 Thread Simon J Welsh
On 1/03/2011, at 4:52 PM, Ron Piggott wrote:

 
 I need help to know how to sort the words / phrases in my array.
 
 Variable name: $words_used
 print_r( $words_used ); Current output: Array ( [187] = Sin [249] = 
 Punished [98] = Sanctuary [596] = Sing [362] = Anointing Oil )
 Desired result: Alphabetical sort: Array ( [362] = Anointing Oil [249] = 
 Punished [98] = Sanctuary [187] = Sin [596] = Sing ) 
 
 The #’s are the auto_increment value of the word in the mySQL database.  The 
 number is not representative of alphabetical order, but the order it was 
 added to the database.
 
 Thank you for your assistance.
 
 Ron
 
 The Verse of the Day
 “Encouragement from God’s Word”
 http://www.TheVerseOfTheDay.info  

Have a look at asort() (http://php.net/asort), which is used to sort arrays but 
maintain the key association. The default search option should work fine for 
you, if not try one of the other SORT_* flags described on the sort() manual 
page.
---
Simon Welsh
Admin of http://simon.geek.nz/

Who said Microsoft never created a bug-free program? The blue screen never, 
ever crashes!

http://www.thinkgeek.com/brain/gimme.cgi?wid=81d520e5e


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting an array of sub-arrays based on a sub-array's key

2009-09-06 Thread Eddie Drapkin
On Sun, Sep 6, 2009 at 6:45 PM, James Colanninoja...@colannino.org wrote:
 Hey everyone.  I have an array that looks like this:

 $main_array[0] = array('key1' = 'vala');
 $main_array[1] = array('key1' = 'valb');
 etc.

 I want to sort the main array based on the value of key1 for each
 sub-array.  I looked at all the array sorting functions, but unless I
 misunderstood something, I didn't see a direct way to do what I want.

 If there were a sorting function in which I could pass as an argument
 the name of a function that compares two elements like qsort in C, I
 could do it easily.  Is there a function like that in PHP?  If not, what
 should I do?

 Thanks everyone!
 James

 --
 PHP General Mailing List (http://www.php.net/)
 To unsubscribe, visit: http://www.php.net/unsub.php



http://us3.php.net/uasort

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting an array of sub-arrays based on a sub-array's key

2009-09-06 Thread James Colannino
Eddie Drapkin wrote:

 http://us3.php.net/uasort

Exactly what I was looking for.  Thanks.

James

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting mySQL query - one order from multiple fields

2009-07-26 Thread George Langley
	In case anyone else was wondering, the command to use is COALESCE()  
as in:


$theQuery = mysql_query(select variousFields from theTable where  
date = '$currDate' ORDER BY COALESCE(rotime2,rotime1,time));


COALESCE() will use one of the variables, being the one it finds a  
value for first, for each record. Note how this differs from a multi  
sort, which sorts by the first field, then subsorts by the second,  
third, etc.

Hope this helps someone.


George Langley
Multimedia Developer, Audio/Video Editor, Musician, Arranger, Composer

http://www.georgelangley.ca
-
On 14-Jun-09, at 8:30 PM, George Langley wrote:

	Hi all. Am trying to sort baseball games by time, where there can  
be up to 3 times listed per game.
	Each game has an original date and time field, plus fields for  
2 rain-out dates/times (rodate1 rotime1, rodate2, rotime2),  
to use if the game gets rained out. Note that rotime1 and rotime2  
are NULL if no time has been entered. Also note that the original  
date and time fields are not changed - they are kept for posterity.
	Usually, the rain-out date is set to a day that the teams were  
already going to play each other again, with the rain-out game  
going first. So need to sort those 2 games in order: rain-out  
first, then normally-scheduled.
	But, I can't just sort on the time field, as the rain-out game  
could now have a different time. I need to use the rotime2 (if it  
exists), else use the rotime1 (if it exists), else use the time.

Can not get my query order to work. One of the variations I've tried:

$theQuery = mysql_query(select variousFields from theTable where  
date = '$currDate' ORDER BY CASE WHEN rotime2 THEN rotime2 WHEN  
rotime1 THEN rotime1 ELSE time);


	Is there a query sort that will work in this case? Is not the  
usual sort by last name, then sort by first name scenario!

Thanks for any pointers.


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting times (SOLVED)

2009-05-16 Thread German Geek
Just a draft i thought should not go unnoticed on the list :-) just cleaning
up.
OK,

How about a super efficient soln where each string is only converted once
and a fast sorting algorithm is used:

?php

function time_sort($a, $b)  {
 static $now = time();

 if (strtotime($a, $now) == strtotime($b, $now)) {
 return 0;
 }
 return (strtotime($a, $now)  strtotime($b, $now) ? -1 : 1;
}

function sortTime($times) {

}
Tim-Hinnerk Heuer

http://www.ihostnz.com
Fred Allen  - California is a fine place to live - if you happen to be an
orange.

2009/2/16 Shawn McKenzie nos...@mckenzies.net

 tedd wrote:
  At 9:31 PM -0600 2/14/09, Shawn McKenzie wrote:
 
  Yeah, hif I had known that you wanted a function where you loop through
  your array twice, that would have done it.  Bravo.
 
  Shawn:
 
  I don't see another way. You go through the array converting string to
  time (seconds), sort, and then convert back. You have to go through the
  array more than once.
 
  Cheers,
 
  tedd
 
 The other way, is the most likely ultra-fast solution I posted.

 --
 Thanks!
 -Shawn
 http://www.spidean.com

 --
 PHP General Mailing List (http://www.php.net/)
 To unsubscribe, visit: http://www.php.net/unsub.php




Re: [PHP] Sorting times (SOLVED)

2009-02-15 Thread tedd

At 9:31 PM -0600 2/14/09, Shawn McKenzie wrote:


Yeah, hif I had known that you wanted a function where you loop through
your array twice, that would have done it.  Bravo.


Shawn:

I don't see another way. You go through the array converting string 
to time (seconds), sort, and then convert back. You have to go 
through the array more than once.


Cheers,

tedd

--
---
http://sperling.com  http://ancientstones.com  http://earthstones.com

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting times (SOLVED)

2009-02-15 Thread Shawn McKenzie
tedd wrote:
 At 9:31 PM -0600 2/14/09, Shawn McKenzie wrote:

 Yeah, hif I had known that you wanted a function where you loop through
 your array twice, that would have done it.  Bravo.
 
 Shawn:
 
 I don't see another way. You go through the array converting string to
 time (seconds), sort, and then convert back. You have to go through the
 array more than once.
 
 Cheers,
 
 tedd
 
The other way, is the most likely ultra-fast solution I posted.

-- 
Thanks!
-Shawn
http://www.spidean.com

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting times

2009-02-14 Thread John Corry
1. convert the string representation of times to timestamps using  
strtotime()

2. sort the timestamps
3. display the timestamps as strings using date('format', timestamp)

Would that work?

John Corry
email: jco...@gmail.com




On Feb 14, 2009, at 4:07 PM, tedd wrote:


Hi gang:

Anyone have/know a routine that will sort an array of times?

For example, a function that would take an array like this:

time[0] ~ '1:30pm'
time[1] ~ '7:30am'
time[2] ~ '12:30pm'

and order it to:

time[0] ~ '7:30am'
time[1] ~ '12:30pm'
time[2] ~ '1:30pm'


Cheers,

tedd


--
---
http://sperling.com  http://ancientstones.com  http://earthstones.com

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php




--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting times

2009-02-14 Thread Shawn McKenzie
John Corry wrote:
 1. convert the string representation of times to timestamps using
 strtotime()
 2. sort the timestamps
 3. display the timestamps as strings using date('format', timestamp)
 
 Would that work?
 
 John Corry
 email: jco...@gmail.com
 
 
 
 
 On Feb 14, 2009, at 4:07 PM, tedd wrote:
 
 Hi gang:

 Anyone have/know a routine that will sort an array of times?

 For example, a function that would take an array like this:

 time[0] ~ '1:30pm'
 time[1] ~ '7:30am'
 time[2] ~ '12:30pm'

 and order it to:

 time[0] ~ '7:30am'
 time[1] ~ '12:30pm'
 time[2] ~ '1:30pm'


 Cheers,

 tedd


 -- 
 ---
 http://sperling.com  http://ancientstones.com  http://earthstones.com

 -- 
 PHP General Mailing List (http://www.php.net/)
 To unsubscribe, visit: http://www.php.net/unsub.php

 

Yes, I would probably store and manipulate times as a timestamp and then
format them for printing, but then there would always be a date
associated with the timestamp as well (whether you need it or not).  So
you could store them in 24hr time format and sort those and then format
to display in the 12 hour format.

-- 
Thanks!
-Shawn
http://www.spidean.com

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting times (SOLVED)

2009-02-14 Thread tedd

At 4:15 PM -0500 2/14/09, John Corry wrote:

1. convert the string representation of times to timestamps using strtotime()
2. sort the timestamps
3. display the timestamps as strings using date('format', timestamp)

Would that work?

John Corry
email: jco...@gmail.com



John:

Bingo -- that worked!

Thanks.

tedd

---

Here's the code.

?php
// == returns a time array sorted

function sortTime($in_times)
{
$time = array();
foreach ($in_times as $t)
{
$time [] = strtotime($t);
}

sort($time);

$sort_time = array();
foreach ($time as $t)
{
$sort_time[] = date('g:ia', $t);
}
return $sort_time;
}
?


--
---
http://sperling.com  http://ancientstones.com  http://earthstones.com

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting times (SOLVED)

2009-02-14 Thread Shawn McKenzie
tedd wrote:
 At 4:15 PM -0500 2/14/09, John Corry wrote:
 1. convert the string representation of times to timestamps using
 strtotime()
 2. sort the timestamps
 3. display the timestamps as strings using date('format', timestamp)

 Would that work?

 John Corry
 email: jco...@gmail.com
 
 
 John:
 
 Bingo -- that worked!
 
 Thanks.
 
 tedd
 
 ---
 
 Here's the code.
 
 ?php
 // == returns a time array sorted
 
 function sortTime($in_times)
 {
 $time = array();
 foreach ($in_times as $t)
 {
 $time [] = strtotime($t);
 }
 
 sort($time);
 
 $sort_time = array();
 foreach ($time as $t)
 {
 $sort_time[] = date('g:ia', $t);
 }
 return $sort_time;
 }
 ?
 
 
Yeah, hif I had known that you wanted a function where you loop through
your array twice, that would have done it.  Bravo.



-- 
Thanks!
-Shawn
http://www.spidean.com

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting Arrays

2008-08-22 Thread Micah Gersten
I believe you'll need a custom sorting function for this.
http://us.php.net/usort

Thank you,
Micah Gersten
onShore Networks
Internal Developer
http://www.onshore.com



Tom Shaw wrote:
 I'm having a problem sorting my array and wondered if anybody had experience
 sorting arrays by their values. What I need to do is resort the array below 

 where the most expensive product shipping price starts at position zero no
 matter how big the array is.

  

 array(2) {

   [0] = array(48) {

 [product_id] = string(2) 34

 [product_name] = string(29) Bears Ball Cap

 [product_ordered_size] = string(5) ADULT

 [product_sales_price] = string(8) 11.90

 [product_shipping_price] = string(4) 7.85

 [product_shipping_extra] = string(4) 0.06

   }

   [1] = array(48) {

 [product_id] = string(2) 37

 [product_name] = string(21) Baldwin L Grand Piano

 [product_ordered_size] = string(5) Grand

 [product_sales_price] = string(8) 11671.90

 [product_shipping_price] = string(6) 500.00

 [product_shipping_extra] = string(6) 450.00

   }

  

 Thanks 

  

 [EMAIL PROTECTED]


   

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting Arrays

2008-08-22 Thread Ashley Sheridan
Yeah, a bubble sorting algorithm should fix it, as it essentially only a
very simple sort required.

Ash
www.ashleysheridan.co.uk
---BeginMessage---
I believe you'll need a custom sorting function for this.
http://us.php.net/usort

Thank you,
Micah Gersten
onShore Networks
Internal Developer
http://www.onshore.com



Tom Shaw wrote:
 I'm having a problem sorting my array and wondered if anybody had experience
 sorting arrays by their values. What I need to do is resort the array below 

 where the most expensive product shipping price starts at position zero no
 matter how big the array is.

  

 array(2) {

   [0] = array(48) {

 [product_id] = string(2) 34

 [product_name] = string(29) Bears Ball Cap

 [product_ordered_size] = string(5) ADULT

 [product_sales_price] = string(8) 11.90

 [product_shipping_price] = string(4) 7.85

 [product_shipping_extra] = string(4) 0.06

   }

   [1] = array(48) {

 [product_id] = string(2) 37

 [product_name] = string(21) Baldwin L Grand Piano

 [product_ordered_size] = string(5) Grand

 [product_sales_price] = string(8) 11671.90

 [product_shipping_price] = string(6) 500.00

 [product_shipping_extra] = string(6) 450.00

   }

  

 Thanks 

  

 [EMAIL PROTECTED]


   

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


---End Message---
-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Re: [PHP] Sorting Arrays

2008-08-22 Thread Robert Cummings
On Fri, 2008-08-22 at 21:04 +0100, Ashley Sheridan wrote:
 Yeah, a bubble sorting algorithm should fix it, as it essentially only
 a very simple sort required.

Why use bubble sort when you can use usort() function with an arbitrary
handler?

Cheers,
Rob.


 
 Ash
 www.ashleysheridan.co.uk
 email message attachment, Forwarded message - Re: [PHP] Sorting
 Arrays
   Forwarded Message 
  From: Micah Gersten [EMAIL PROTECTED]
  To: Tom Shaw [EMAIL PROTECTED]
  Cc: php-general@lists.php.net
  Subject: Re: [PHP] Sorting Arrays
  Date: Fri, 22 Aug 2008 14:18:53 -0500
  
  I believe you'll need a custom sorting function for this.
  http://us.php.net/usort
  
  Thank you,
  Micah Gersten
  onShore Networks
  Internal Developer
  http://www.onshore.com
  
  
  
  Tom Shaw wrote:
   I'm having a problem sorting my array and wondered if anybody had 
   experience
   sorting arrays by their values. What I need to do is resort the array 
   below 
  
   where the most expensive product shipping price starts at position zero no
   matter how big the array is.
  

  
   array(2) {
  
 [0] = array(48) {
  
   [product_id] = string(2) 34
  
   [product_name] = string(29) Bears Ball Cap
  
   [product_ordered_size] = string(5) ADULT
  
   [product_sales_price] = string(8) 11.90
  
   [product_shipping_price] = string(4) 7.85
  
   [product_shipping_extra] = string(4) 0.06
  
 }
  
 [1] = array(48) {
  
   [product_id] = string(2) 37
  
   [product_name] = string(21) Baldwin L Grand Piano
  
   [product_ordered_size] = string(5) Grand
  
   [product_sales_price] = string(8) 11671.90
  
   [product_shipping_price] = string(6) 500.00
  
   [product_shipping_extra] = string(6) 450.00
  
 }
  

  
   Thanks 
  

  
   [EMAIL PROTECTED]
  
  
 
  
 -- 
 PHP General Mailing List (http://www.php.net/)
 To unsubscribe, visit: http://www.php.net/unsub.php
-- 
http://www.interjinn.com
Application and Templating Framework for PHP


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting Arrays

2008-08-22 Thread Micah Gersten


Robert Cummings wrote:
 On Fri, 2008-08-22 at 21:04 +0100, Ashley Sheridan wrote:
   
 Yeah, a bubble sorting algorithm should fix it, as it essentially only
 a very simple sort required.
 

 Why use bubble sort when you can use usort() function with an arbitrary
 handler?

 Cheers,
 Rob.

   
Exactly.  That's one reason why I love PHP.  They have functions that do
things you have to write subroutines for in other languages.

Thank you,
Micah Gersten
onShore Networks
Internal Developer
http://www.onshore.com



-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting Arrays

2008-08-22 Thread Jim Lucas

Tom Shaw wrote:

I'm having a problem sorting my array and wondered if anybody had experience
sorting arrays by their values. What I need to do is resort the array below 


where the most expensive product shipping price starts at position zero no
matter how big the array is.

 


array(2) {

  [0] = array(48) {

[product_id] = string(2) 34

[product_name] = string(29) Bears Ball Cap

[product_ordered_size] = string(5) ADULT

[product_sales_price] = string(8) 11.90

[product_shipping_price] = string(4) 7.85

[product_shipping_extra] = string(4) 0.06

  }

  [1] = array(48) {

[product_id] = string(2) 37

[product_name] = string(21) Baldwin L Grand Piano

[product_ordered_size] = string(5) Grand

[product_sales_price] = string(8) 11671.90

[product_shipping_price] = string(6) 500.00

[product_shipping_extra] = string(6) 450.00

  }

 

Thanks 

 


[EMAIL PROTECTED]




Everything can be done with three custom lines of code, the rest is PHP 
existing function calls.


http://us3.php.net/manual/en/function.array-multisort.php

Example #3 Sorting database results

I expanded your list below and randomly added some data...  Anyways, 
replace my $ar array definition with your array and you should be good 
to go.  One question though, is this coming from a DB?  If so, why not 
do the sorting in the SQL call instead of PHP?  Just a thought.



plaintext?php

$ar = array(
  array(
product_id = 34,
product_name = Bears Ball Cap #34,
product_ordered_size = ADULT,
product_sales_price = 11.90,
product_shipping_price = 7.85,
product_shipping_extra = 0.06,
  ),
  array(
product_id = 35,
product_name = Baldwin L Grand Piano #35,
product_ordered_size = Grand,
product_sales_price = 11671.90,
product_shipping_price = 51.00,
product_shipping_extra = 450.00,
  ),
  array(
product_id = 36,
product_name = Baldwin L Grand Piano #36,
product_ordered_size = Grand,
product_sales_price = 11671.90,
product_shipping_price = 500.00,
product_shipping_extra = 450.00,
  ),
  array(
product_id = 37,
product_name = Baldwin L Grand Piano #37,
product_ordered_size = Grand,
product_sales_price = 11671.90,
product_shipping_price = 5000.00,
product_shipping_extra = 450.00,
  ),
  array(
product_id = 38,
product_name = Baldwin L Grand Piano #38,
product_ordered_size = Grand,
product_sales_price = 11671.90,
product_shipping_price = 50.00,
product_shipping_extra = 450.00,
  ),
  array(
product_id = 39,
product_name = Baldwin L Grand Piano #39,
product_ordered_size = Grand,
product_sales_price = 11671.90,
product_shipping_price = 1.00,
product_shipping_extra = 450.00,
  )
);

foreach ( $ar AS $k = $v ) {
  $p_shipping_price[$k] = $v['product_shipping_price'];
}

array_multisort($p_shipping_price, SORT_DESC, $ar);

var_dump($ar);

?




--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting files in a directory

2007-08-09 Thread Chad Robinson

Steve Marquez wrote:

I know this code does not work, but I was curious if someone can take a look
and tell me what is wrong? Thank you so much.
  

Re-indent your code properly. If you do it will look like:

?php
$pattern = .html*|.php*;

if (is_dir(files/)) {
   if ($dh = opendir(files/)) {
   echo select name=\file\ size=\8\;
   while (($file = readdir($dh)) !== false) {
   if (ereg($pattern, $file))
   if(strpos($file,'.')0) {
   $file_array = array($file);
   sort ($file_array);

   foreach($file_array as $key = $value) {
   echo option value=\$value\.$value./option;
   }
   }
   }
   echo /select;
   closedir($dh);
   }
   }
?

You have a number of things you need to look at here. First, you don't have a final 
closing brace for your opening if() statement. Second, you're outputting the 
option tags INSIDE the while loop that reads the directory, so for every file 
you read your options list will get bigger. Well, it would, but you're also not using 
the right array append method; it should be:
   $file_array[] = $file;

Next, you don't want to sort the array every time you add a file to it - just 
do it once when you're done.

Try this:
?php
$pattern = .html*|.php*;

if (is_dir(files/)  $dh = opendir(files/)) {
   echo 'select name=file size=8';
   while (($file = readdir($dh)) !== false) {
   if (!ereg($pattern, $file)) continue;
   if(strpos($file,'.')1) continue;
   $file_array[] = $file;
   }

   sort ($file_array);
   foreach($file_array as $value) {
   echo 'option value=' . $value . '' . $value . '/option';
   }
   echo /select;
   closedir($dh);
}
?

Syntax check is left as an exe3rcise for the student. =)

Regards,
Chad

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting files in a directory

2007-08-08 Thread Chris

Steve Marquez wrote:

Greetings,

I have some code that opens a directory and displays the files. I want to
display the files in Alphabetical order.

I know this code does not work, but I was curious if someone can take a look
and tell me what is wrong? Thank you so much.


[ I hope the indenting is because you're posting to the list - 
tabs/spaces make it a lot easier to follow what's going on ]


You have this:

$file_array = array($file);
sort ($file_array);

foreach($file_array as $key = $value) {
echo option value=\$value\.$value./option;
}

You're sorting one element of an array and then printing it out.

Not what you want.

Try this cut down version:

http://pastebin.com/m5bcadd77

Also note that in your example, if a directory can't be opened for 
whatever reason, then you don't get a select box at all - is that what 
you want to do?


--
Postgresql  php tutorials
http://www.designmagick.com/

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting via PHP or MySQL?

2007-05-13 Thread Richard Lynch
On Thu, May 10, 2007 1:00 pm, James Tu wrote:
 (I've cross posted at the MySQL list as well)

 Here's an example with a simple table:

 describe collection;

 +--+-+--+-
 +-++
 | Field| Type| Null | Key |
 Default | Extra  |
 +--+-+--+-
 +-++
 | id   | bigint(20) unsigned |  | PRI |
 NULL| auto_increment |
 | receiver_id  | bigint(20) unsigned |  | MUL |
 0   ||
 | set_type_id  | int(2) unsigned |  | |
 0   ||
 | card_id  | int(3) unsigned |  | |
 0   ||
 | completed_set_id | bigint(20) unsigned |  | |
 0   ||
 | created_on_gmt   | datetime|  | | -00-00
 00:00:00 ||
 +--+-+--+-
 +-++


 I want to end up with two PHP arrays.  One for set_type_id = 22 and
 one for set_type_id=21.

 (1) one query method:
 SELECT * from collection WHERE set_type_id=22 OR set_type_id=21;
 ...do query...
 while( $row = $this-db-fetch_array_row() ){

/*
   if ($row['set_type_id'] == 21){
   $array_a[] = $row;
   } else {
   $array_b[] = $row;
   }
*/
$array[$row['set_type_id']][] = $row;

 }

var_dump($array);

You'll have one array of all the 21s, and one of all the 22s.

 Which method is better?  Take a hit using MySQL or take a hit using
 PHP?

Honestly, is really doesn't make a damn bit of difference unless you
have ZILLIONS of records in the first place, in which case you
shouldn't be sucking them all down at once anyway...

So write whatever you can figure out what's going on next month/year
without beating your head against the wall trying to read your own
code.

Worry about optimizing only after you identify bottlenecks.

Anything else is optimize-wankery.

-- 
Some people have a gift link here.
Know what I want?
I want you to buy a CD from some indie artist.
http://cdbaby.com/browse/from/lynch
Yeah, I get a buck. So?

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] sorting via PHP or MySQL?

2007-05-10 Thread Brad Fuller
James Tu wrote:
 (I've cross posted at the MySQL list as well)
 
 Here's an example with a simple table:
 
 describe collection;
 
 +--+-+--+-
 +-++
 Field| Type| Null | Key |
 Default | Extra  |
 +--+-+--+-
 +-++
 id   | bigint(20) unsigned |  | PRI |
 NULL| auto_increment |
 receiver_id  | bigint(20) unsigned |  | MUL |
 0   ||
 set_type_id  | int(2) unsigned |  | |
 0   ||
 card_id  | int(3) unsigned |  | |
 0   ||
 completed_set_id | bigint(20) unsigned |  | |
 0   ||
 created_on_gmt   | datetime|  | | -00-00
 00:00:00 ||
 +--+-+--+-
 +-++
 
 
 I want to end up with two PHP arrays.  One for set_type_id = 22 and
 one for set_type_id=21. 
 
 (1) one query method:
 SELECT * from collection WHERE set_type_id=22 OR set_type_id=21;
 ...do query... while( $row = $this-db-fetch_array_row() ){
   if ($row['set_type_id'] == 21){
   $array_a[] = $row;
   } else {
   $array_b[] = $row;
   }
 }
 
 
 (2) two query method:
 SELECT * from collection WHERE set_type_id=22;
 ...do query...
 while( $row = $this-db-fetch_array_row() ){
   $array_a[] = $row;
 }
 
 SELECT * from collection WHERE set_type_id=21;
 ...do query...
 while( $row = $this-db-fetch_array_row() ){
   $array_b[] = $row;
 }
 
 
 Which method is better?  Take a hit using MySQL or take a hit using
 PHP? 
 
 -James


I really don't think you'd notice any difference, unless your table contains
a large amount of data and is not properly indexed.  And if that were the
case, you'd notice a hit on just one query anyway.

I'd stick with the 2 query model, but instead of creating arrays, just loop
through the query results to output your data, no sense looping to make an
array when you're just going to end up looping through the array to output;
that seems redundant to me :P

Just my $.02

-B

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting via PHP or MySQL?

2007-05-10 Thread Robert Cummings
On Thu, 2007-05-10 at 14:00 -0400, James Tu wrote:
 (I've cross posted at the MySQL list as well)
 
 Here's an example with a simple table:
 
 describe collection;
 
 +--+-+--+- 
 +-++
 | Field| Type| Null | Key |  
 Default | Extra  |
 +--+-+--+- 
 +-++
 | id   | bigint(20) unsigned |  | PRI |  
 NULL| auto_increment |
 | receiver_id  | bigint(20) unsigned |  | MUL |  
 0   ||
 | set_type_id  | int(2) unsigned |  | |  
 0   ||
 | card_id  | int(3) unsigned |  | |  
 0   ||
 | completed_set_id | bigint(20) unsigned |  | |  
 0   ||
 | created_on_gmt   | datetime|  | | -00-00  
 00:00:00 ||
 +--+-+--+- 
 +-++
 
 
 I want to end up with two PHP arrays.  One for set_type_id = 22 and  
 one for set_type_id=21.
 
 (1) one query method:
 SELECT * from collection WHERE set_type_id=22 OR set_type_id=21;
 ...do query...
 while( $row = $this-db-fetch_array_row() ){
   if ($row['set_type_id'] == 21){
   $array_a[] = $row;
   } else {
   $array_b[] = $row;  
   }
 }
 
 
 (2) two query method:
 SELECT * from collection WHERE set_type_id=22;
 ...do query...
 while( $row = $this-db-fetch_array_row() ){
   $array_a[] = $row;
 }
 
 SELECT * from collection WHERE set_type_id=21;
 ...do query...
 while( $row = $this-db-fetch_array_row() ){
   $array_b[] = $row;
 }
 
 
 Which method is better?  Take a hit using MySQL or take a hit using PHP?

Single query method is superior in your example.

Cheers,
Rob.
-- 
..
| InterJinn Application Framework - http://www.interjinn.com |
::
| An application and templating framework for PHP. Boasting  |
| a powerful, scalable system for accessing system services  |
| such as forms, properties, sessions, and caches. InterJinn |
| also provides an extremely flexible architecture for   |
| creating re-usable components quickly and easily.  |
`'

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting via PHP or MySQL?

2007-05-10 Thread Larry Garfield
A somewhat more extensible version of the 1 query method:

http://www.garfieldtech.com/blog/php-group-by

If you will only ever have 2 values there, then either method is probably 
fine.  The php group by method (above) is more extensible if you're going 
to have a variable or arbitrary number of groups, though.

Cheers.

On Thursday 10 May 2007, James Tu wrote:
 (I've cross posted at the MySQL list as well)

 Here's an example with a simple table:

 describe collection;

 +--+-+--+-
 +-++

 | Field| Type| Null | Key |

 Default | Extra  |
 +--+-+--+-
 +-++

 | id   | bigint(20) unsigned |  | PRI |

 NULL| auto_increment |

 | receiver_id  | bigint(20) unsigned |  | MUL |

 0   ||

 | set_type_id  | int(2) unsigned |  | |

 0   ||

 | card_id  | int(3) unsigned |  | |

 0   ||

 | completed_set_id | bigint(20) unsigned |  | |

 0   ||

 | created_on_gmt   | datetime|  | | -00-00

 00:00:00 ||
 +--+-+--+-
 +-++


 I want to end up with two PHP arrays.  One for set_type_id = 22 and
 one for set_type_id=21.

 (1) one query method:
 SELECT * from collection WHERE set_type_id=22 OR set_type_id=21;
 ...do query...
 while( $row = $this-db-fetch_array_row() ){
   if ($row['set_type_id'] == 21){
   $array_a[] = $row;
   } else {
   $array_b[] = $row;
   }
 }


 (2) two query method:
 SELECT * from collection WHERE set_type_id=22;
 ...do query...
 while( $row = $this-db-fetch_array_row() ){
   $array_a[] = $row;
 }

 SELECT * from collection WHERE set_type_id=21;
 ...do query...
 while( $row = $this-db-fetch_array_row() ){
   $array_b[] = $row;
 }


 Which method is better?  Take a hit using MySQL or take a hit using PHP?

 -James


-- 
Larry Garfield  AIM: LOLG42
[EMAIL PROTECTED]   ICQ: 6817012

If nature has made any one thing less susceptible than all others of 
exclusive property, it is the action of the thinking power called an idea, 
which an individual may exclusively possess as long as he keeps it to 
himself; but the moment it is divulged, it forces itself into the possession 
of every one, and the receiver cannot dispossess himself of it.  -- Thomas 
Jefferson

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting multi array

2007-04-25 Thread Frank Arensmeier
Jon, I would suggest that you should have a look at the function  
array_multisort. See the manual for details on what this function  
is capable of.


//frank
25 apr 2007 kl. 01.58 skrev Jon Bennett:


hi,

I have the following array, which I need to sort by quantity...

Array
(
   [2408] = Array
   (
   [name] = Havaianas Top Pink Crystal
   [size] = 5 (37/38)
   [quantity] = 4
   )

   [3388] = Array
   (
   [name] = Havaianas Brazil Silver
   [size] = 6/7 (39/40)
   [quantity] = 6
   )

   [2666] = Array
   (
   [name] = Havaianas Brasil Black
   [size] = 8/9 (41/42)
   [quantity] = 1
   )

   [3210] = Array
   (
   [name] = Havaianas Margaridas Yellow
   [size] = 5 (37/38)
   [quantity] = 1
   )

   [2552] = Array
   (
   [name] = Havaianas Flash White
   [size] = 5 (37/38)
   [quantity] = 1
   )
)

I need to keep the indexes if poss.

Many thanks,

jon

--


jon bennett
t: +44 (0) 1225 341 039 w: http://www.jben.net/
iChat (AIM): jbendotnet Skype: jon-bennett

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] sorting multi array

2007-04-25 Thread Chris Boget
 I have the following array, which I need to sort by quantity...
 I need to keep the indexes if poss.

This may not be the most elegant solution.  Let's call your array
$origArray

$tmpArray = array();
foreach( $origArray as $elKey = $elArray ) {
  $tmpArray[$elArray['quantity']] = $elKey;

}

if( ksort( $tmpArray )) {
  $sortedArray = array();
  foreach( $tmpArray as $elKey ) {
$sortedArray[$elKey] = $origArray[$elKey];

  }
  echo 'Original: pre' . print_r( $origArray, TRUE ) '/prebr';
  echo 'Sorted: pre' . print_r( $sortedArray, TRUE ) '/pre';

} else {
  echo 'Sorry, couldn\'t sort';

}

thnx,
Chris

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] sorting multi array

2007-04-25 Thread Zoltán Németh
2007. 04. 25, szerda keltezéssel 11.39-kor Chris Boget ezt írta:
  I have the following array, which I need to sort by quantity...
  I need to keep the indexes if poss.
 
 This may not be the most elegant solution.  Let's call your array
 $origArray
 
 $tmpArray = array();
 foreach( $origArray as $elKey = $elArray ) {
   $tmpArray[$elArray['quantity']] = $elKey;
 
 }
 
 if( ksort( $tmpArray )) {
   $sortedArray = array();
   foreach( $tmpArray as $elKey ) {
 $sortedArray[$elKey] = $origArray[$elKey];
 
   }
   echo 'Original: pre' . print_r( $origArray, TRUE ) '/prebr';
   echo 'Sorted: pre' . print_r( $sortedArray, TRUE ) '/pre';
 
 } else {
   echo 'Sorry, couldn\'t sort';
 
 }

this won't work if he has the same quantity for several keys, I think

greets
Zoltán Németh

 
 thnx,
 Chris
 

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting multi array

2007-04-25 Thread Chris Boget

this won't work if he has the same quantity for several keys, I think


Yes, you are correct.  If that is the case, then you would just need to 
change the following line


$tmpArray[$elArray['quantity']] = $elKey;

to

$tmpArray[$elArray['quantity']][] = $elKey;

then change logic in this loop:

foreach( $tmpArray as $elKey ) {

to handle the additional array.  If additional sorting needs to occur for 
those keys that have the same quantity then I think recursion will be in 
order.


thnx,
Chris

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting multi array

2007-04-25 Thread [EMAIL PROTECTED]
array_multisort accepts column arrays but here you try to sort row based  
arrays.


try this:
?
class ArrayUtility
{
/* Sorts an array by a member */
static private $sortMember;
static function sortByMember($array, $member)
{
self::$sortMember = $member;
usort($array, array('ArrayUtility', 'compareMember'));
}

static function compareMember($a, $b)
{
return $a[self::$sortMember]  $b[self::$sortMember];
}
}


ArrayUtility::sortByMember($array, 'quantity');

?
Am 25.04.2007, 12:36 Uhr, schrieb Frank Arensmeier  
[EMAIL PROTECTED]:


Jon, I would suggest that you should have a look at the function  
array_multisort. See the manual for details on what this function is  
capable of.


//frank
25 apr 2007 kl. 01.58 skrev Jon Bennett:


hi,

I have the following array, which I need to sort by quantity...

Array
(
   [2408] = Array
   (
   [name] = Havaianas Top Pink Crystal
   [size] = 5 (37/38)
   [quantity] = 4
   )

   [3388] = Array
   (
   [name] = Havaianas Brazil Silver
   [size] = 6/7 (39/40)
   [quantity] = 6
   )

   [2666] = Array
   (
   [name] = Havaianas Brasil Black
   [size] = 8/9 (41/42)
   [quantity] = 1
   )

   [3210] = Array
   (
   [name] = Havaianas Margaridas Yellow
   [size] = 5 (37/38)
   [quantity] = 1
   )

   [2552] = Array
   (
   [name] = Havaianas Flash White
   [size] = 5 (37/38)
   [quantity] = 1
   )
)

I need to keep the indexes if poss.

Many thanks,

jon

--

jon bennett
t: +44 (0) 1225 341 039 w: http://www.jben.net/
iChat (AIM): jbendotnet Skype: jon-bennett

--PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php





--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting multi array

2007-04-25 Thread Myron Turner

Jon Bennett wrote:

hi,

I have the following array, which I need to sort by quantity...

Array
(
   [2408] = Array
   (
   [name] = Havaianas Top Pink Crystal
   [size] = 5 (37/38)
   [quantity] = 4
   )

   [3388] = Array
   (
   [name] = Havaianas Brazil Silver
   [size] = 6/7 (39/40)
   [quantity] = 6
   )

   [2666] = Array
   (
   [name] = Havaianas Brasil Black
   [size] = 8/9 (41/42)
   [quantity] = 1
   )

   [3210] = Array
   (
   [name] = Havaianas Margaridas Yellow
   [size] = 5 (37/38)
   [quantity] = 1
   )

   [2552] = Array
   (
   [name] = Havaianas Flash White
   [size] = 5 (37/38)
   [quantity] = 1
   )
)

I need to keep the indexes if poss.

Many thanks,

jon


This works for me:


function cmp($a, $b)
{
   $aq = $a['quantity'];
   $bq = $b['quantity'];

   if ($a == $b) {
   return 0;
   }
   return ($aq  $bq) ? -1 : 1;
}

uasort($data, cmp);

To reverse the sort order:  return ($aq  $bq) ? -1 : 1;

--

_
Myron Turner
http://www.room535.org
http://www.bstatzero.org
http://www.mturner.org/XML_PullParser/

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting multi array

2007-04-25 Thread Richard Lynch
Search the archives for multisort array and you should find this
thread a few thousand times...

On Tue, April 24, 2007 6:58 pm, Jon Bennett wrote:
 hi,

 I have the following array, which I need to sort by quantity...

 Array
 (
 [2408] = Array
 (
 [name] = Havaianas Top Pink Crystal
 [size] = 5 (37/38)
 [quantity] = 4
 )

 [3388] = Array
 (
 [name] = Havaianas Brazil Silver
 [size] = 6/7 (39/40)
 [quantity] = 6
 )

 [2666] = Array
 (
 [name] = Havaianas Brasil Black
 [size] = 8/9 (41/42)
 [quantity] = 1
 )

 [3210] = Array
 (
 [name] = Havaianas Margaridas Yellow
 [size] = 5 (37/38)
 [quantity] = 1
 )

 [2552] = Array
 (
 [name] = Havaianas Flash White
 [size] = 5 (37/38)
 [quantity] = 1
 )
 )

 I need to keep the indexes if poss.

 Many thanks,

 jon

 --


 jon bennett
 t: +44 (0) 1225 341 039 w: http://www.jben.net/
 iChat (AIM): jbendotnet Skype: jon-bennett

 --
 PHP General Mailing List (http://www.php.net/)
 To unsubscribe, visit: http://www.php.net/unsub.php




-- 
Some people have a gift link here.
Know what I want?
I want you to buy a CD from some indie artist.
http://cdbaby.com/browse/from/lynch
Yeah, I get a buck. So?

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting a multidimensional array

2007-02-08 Thread Roman Neuhauser
# [EMAIL PROTECTED] / 2007-02-08 14:08:13 +:
 Hi all. I am building an online events directory and as part of the system
 users can search for events by date, category etc.
 
 The logic involved in finding events that match the user-entered dates works
 like so:
 
 1. we create a range of dates from the start and end dates specified by the
 user
 2. we then poll the database for any events that encompass or intersect this
 range (using the start_date and end_date fields from events table).
 3. we then find out the frequency of the event ie weekly, monthly and then
 map out its lifetime.
 4. we then go through those dates, and for any that match a date in the user
 range, the event on that date (ie all it details, name, venue, date, start
 time etc) is added to an array.

Order in the database. SELECT ... ORDER BY.

-- 
How many Vietnam vets does it take to screw in a light bulb?
You don't know, man.  You don't KNOW.
Cause you weren't THERE. http://bash.org/?255991

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting a multidimensional array

2007-02-08 Thread Dave Goodchild

Thanks for that - can't do that as all I know in the database is the start
and end date for each event (so I don't have to create mapping tables and
perform massive joins), the rest is handle dynamically.

I think I can do it using usort, this seems to work, any comments?

function compare($x, $y) {

if (($x['date'] == $y['date'])  ($x['start_time'] ==
$y['start_time'])) {
   return 0;
   } else if (($x['date'] == $y['date'])  ($x['start_time'] 
$y['start_time'])) {
   return -1;
   } else if (($x['date'] == $y['date'])  ($x['start_time'] 
$y['start_time'])) {
   return 1;
   } else if ($x['date']  $y['date']) {
 return -1;
} else {
 return 1;
   }
   }


Re: [PHP] Sorting a multidimensional array

2007-02-08 Thread Németh Zoltán
array_multisort?

http://php.net/manual/en/function.array-multisort.php

hope that helps
Zoltán Németh

On cs, 2007-02-08 at 14:08 +, Dave Goodchild wrote:
 Hi all. I am building an online events directory and as part of the system
 users can search for events by date, category etc.
 
 The logic involved in finding events that match the user-entered dates works
 like so:
 
 1. we create a range of dates from the start and end dates specified by the
 user
 2. we then poll the database for any events that encompass or intersect this
 range (using the start_date and end_date fields from events table).
 3. we then find out the frequency of the event ie weekly, monthly and then
 map out its lifetime.
 4. we then go through those dates, and for any that match a date in the user
 range, the event on that date (ie all it details, name, venue, date, start
 time etc) is added to an array.
 
 ...etc etc
 
 So we eventually have a large multidimensional array whose elements contain
 arrays of events that fall on a specific date.
 
 I am using usort to ensure the events are sorted by date, but I also want to
 sort by time, for instance if there are five events on one day I want to
 sort them by start_time.
 
 Here's an example of how the event array looks:
 
 element [0] contains an array as follows ('date', 'name' venue',
 'start_time', 'category...');
 element [1] contains an array as follows ('date', 'name' venue',
 'start_time', 'category...');
 
 I tried using array_multisort but it didn't seem to do what I wanted. I want
 to sort by date, then start_time if the dates are equivalent.
 
 Any ideas?
 
 

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] Sorting a multidimensional array

2007-02-08 Thread Edward Kay
How about this:
http://uk.php.net/manual/en/function.array-multisort.php#53779

Edward

 -Original Message-
 From: Dave Goodchild [mailto:[EMAIL PROTECTED]
 Sent: 08 February 2007 14:30
 To: Roman Neuhauser
 Cc: php-general@lists.php.net
 Subject: Re: [PHP] Sorting a multidimensional array


 Thanks for that - can't do that as all I know in the database is the start
 and end date for each event (so I don't have to create mapping tables and
 perform massive joins), the rest is handle dynamically.

 I think I can do it using usort, this seems to work, any comments?

 function compare($x, $y) {

  if (($x['date'] == $y['date'])  ($x['start_time'] ==
 $y['start_time'])) {
 return 0;
 } else if (($x['date'] == $y['date'])  ($x['start_time'] 
 $y['start_time'])) {
 return -1;
 } else if (($x['date'] == $y['date'])  ($x['start_time'] 
 $y['start_time'])) {
 return 1;
 } else if ($x['date']  $y['date']) {
   return -1;
  } else {
   return 1;
 }
 }



-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting issue

2007-02-08 Thread tg-php
Paul's probably right..  putting the sorting values in a table would be eaiser 
to maintain.  I don't know what I was thinking with the whole then you don't 
HAVE to create a table.  Both ways work..  but especially if you think the 
positions may change, then it'll be tons easier to update if they're in a table.

-TG

= = = Original message = = =

= = = Original message = = =
I need to sort the results of a DB query based on the hierarchy of positions
within an organization. Since they are not necessarily alphabetical, the
best I can come up with is to assign a numerical value in a separate table
to each position, and reference that to sort it.


At 2/7/2007 01:10 PM, [EMAIL PROTECTED] wrote:
Well, kind of ugly but you can do something like this:

SELECT Position, CASE Position WHEN 'CEO' THEN 1 WHEN 'COO' THEN 2 
WHEN 'CFO' THEN 3 WHEN 'HR' THEN 4 ELSE 99 END AS PositionSort
FROM SomeTable
ORDER BY PositionSort

That way you're not creating a whole new table to store the sorting values.


If I might offer alternative advice, I *would* create a separate 
table of positions  sort sequence values, so that all the data can 
be edited in one mode (e.g., phpMyAdmin).  If some of your data is in 
MySQL and some of it's embedded in a query in a PHP script, it will 
be a little bit more of a hassle to maintain and a little more 
cryptic for the next developer who has to figure out what you've done 
after you abruptly run off to Tahiti.

SELECT Positions.Sort, Employees.Position, Employees.LastName, etc
FROM Employees, Positions
WHERE Employees.Position = Positions.Position
ORDER BY Positions.Sort, Employees.LastName

(Assuming more than one employee per position, I figure you'd want a 
secondary sort criterion.)

Regards,

Paul
__

Paul Novitski
Juniper Webcraft Ltd.
http://juniperwebcraft.com 


___
Sent by ePrompter, the premier email notification software.
Free download at http://www.ePrompter.com.

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting issue

2007-02-07 Thread tg-php
Well, kind of ugly but you can do something like this:

SELECT Position, CASE Position WHEN 'CEO' THEN 1 WHEN 'COO' THEN 2 WHEN 'CFO' 
THEN 3 WHEN 'HR' THEN 4 ELSE 99 END AS PositionSort
FROM SomeTable
ORDER BY PositionSort


That way you're not creating a whole new table to store the sorting values.

You can also just put the CASE sequence in your ORDER BY (I believe) so it 
doesn't get returned as a value.  Didn't test that, but it's a little thing 
either way.

-TG



= = = Original message = = =

I have been trying to figure out how to get this to work for a couple of
days.

 

I need to sort the results of a DB query based on the hierarchy of positions
within an organization. Since they are not necessarily alphabetical, the
best I can come up with is to assign a numerical value in a separate table
to each position, and reference that to sort it.

 

Is this the best way to do this? Or is there some other trick someone can
clue me in on?

 

My code now runs the query, and with a 

 

while ($row = mysql_fetch_assoc($result))



 *put results into an array*



 

statement I put each entry into an array

 

then I sort it like so.

 

array_multisort($array);

$count = 0;

while (isset ($array[$count]))



*display results in a table*

$count++;



 

 

 

Thanks,

 

Don


___
Sent by ePrompter, the premier email notification software.
Free download at http://www.ePrompter.com.

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting issue

2007-02-07 Thread Paul Novitski



= = = Original message = = =
I need to sort the results of a DB query based on the hierarchy of positions
within an organization. Since they are not necessarily alphabetical, the
best I can come up with is to assign a numerical value in a separate table
to each position, and reference that to sort it.



At 2/7/2007 01:10 PM, [EMAIL PROTECTED] wrote:

Well, kind of ugly but you can do something like this:

SELECT Position, CASE Position WHEN 'CEO' THEN 1 WHEN 'COO' THEN 2 
WHEN 'CFO' THEN 3 WHEN 'HR' THEN 4 ELSE 99 END AS PositionSort

FROM SomeTable
ORDER BY PositionSort

That way you're not creating a whole new table to store the sorting values.



If I might offer alternative advice, I *would* create a separate 
table of positions  sort sequence values, so that all the data can 
be edited in one mode (e.g., phpMyAdmin).  If some of your data is in 
MySQL and some of it's embedded in a query in a PHP script, it will 
be a little bit more of a hassle to maintain and a little more 
cryptic for the next developer who has to figure out what you've done 
after you abruptly run off to Tahiti.


SELECT Positions.Sort, Employees.Position, Employees.LastName, etc
FROM Employees, Positions
WHERE Employees.Position = Positions.Position
ORDER BY Positions.Sort, Employees.LastName

(Assuming more than one employee per position, I figure you'd want a 
secondary sort criterion.)


Regards,

Paul
__

Paul Novitski
Juniper Webcraft Ltd.
http://juniperwebcraft.com 


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting multidimensional arrays

2006-11-16 Thread Robert Cummings
On Thu, 2006-11-16 at 15:28 +, Dave Goodchild wrote:
 Hi all. I have a multidimensional array here:
 
 Bums [name]= string(13) Tits And Bums [3]= string(19) The Pleasure

 [--SNIP--]

 ...which comprises a set of returned results for an events search - with the
 date computed dynamically and added to the end of the array in each case.
 What I want to do with this data is display the array in an html table,
 sorted by the date. At the moment the display shows each event from earliest
 to last date, then the next event from earliest to last etc. What I want to
 do is display all the data from earliest to last date - my question is, how
 do I sort the entire array based on the date value in the second level
 array?

usort()

Cheers,
Rob.
-- 
..
| InterJinn Application Framework - http://www.interjinn.com |
::
| An application and templating framework for PHP. Boasting  |
| a powerful, scalable system for accessing system services  |
| such as forms, properties, sessions, and caches. InterJinn |
| also provides an extremely flexible architecture for   |
| creating re-usable components quickly and easily.  |
`'

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting multidimensional arrays

2006-11-16 Thread Dave Goodchild

Result. Cheers!

On 11/16/06, Robert Cummings [EMAIL PROTECTED] wrote:


On Thu, 2006-11-16 at 15:28 +, Dave Goodchild wrote:
 Hi all. I have a multidimensional array here:

 Bums [name]= string(13) Tits And Bums [3]= string(19) The
Pleasure

 [--SNIP--]

 ...which comprises a set of returned results for an events search - with
the
 date computed dynamically and added to the end of the array in each
case.
 What I want to do with this data is display the array in an html table,
 sorted by the date. At the moment the display shows each event from
earliest
 to last date, then the next event from earliest to last etc. What I want
to
 do is display all the data from earliest to last date - my question is,
how
 do I sort the entire array based on the date value in the second level
 array?

usort()

Cheers,
Rob.
--
..
| InterJinn Application Framework - http://www.interjinn.com |
::
| An application and templating framework for PHP. Boasting  |
| a powerful, scalable system for accessing system services  |
| such as forms, properties, sessions, and caches. InterJinn |
| also provides an extremely flexible architecture for   |
| creating re-usable components quickly and easily.  |
`'





--
http://www.web-buddha.co.uk


Re: [PHP] Sorting MySQL queries

2006-11-07 Thread Dotan Cohen

On 07/11/06, [EMAIL PROTECTED]
[EMAIL PROTECTED] wrote:

you really need to deal with this issue at the database design/data
entry level. doing things on the sort to exclude (otherwise undefined)
initial articles (as some have suggested) is very maintenance heavy as
you have to update the sort portion for every language your data are
entered in. additionally, an initial word that's an initial article in
one language may not be in another.

at the database design/data entry level the common approaches include:

  - a separate field for initial articles
  - separate sort and print fields
  - an initial article offset indicator that is used for sorting

the first of these is probably the easiest and most portable. the last
is easy, but probably the least portable. i consider the separate
print/sort fields to be the least desirable since it's a lot of
redundant data that has to be managed and maintained.

in my experience, if you encounter a setup that doesn't support the
proper handling of initial articles it's best to fix things at the
database/data entry level as soon as possible -- otherwise the
resolution just gets more expensive (however you define that).



Although I wouldn't have known to define it as such, I also don't like
the idea of redundant data littering the DB. But it does seems to be
the easiest method to implement as far as coding, and the fastest way
to retrieve the data.

Dotan Cohen

http://what-is-what.com/what_is/xml.html
http://essentialinux.com/

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting MySQL queries

2006-11-06 Thread tedd

At 3:13 PM +0200 11/5/06, Dotan Cohen wrote:

I have a list of subjects, such as Linux, Open Source, and the
World Wide Web. The subjects are stored in a database and being
retrieved via php. I currently organize them alphabetically with SQL's
ORDER BY ASC argument, however, if there is a preceding the  or a 
then that is considered as part of the alphabetical order. Thus, all
the subjects starting with the  are grouped together, as are the
subjects starting with a . How can I order by ascending, without
taking the preceding the  or a  into account?

Thanks in advance.

Dotan Cohen



Dotan:

In your table, set up a sort field. That way there will be no 
interpolation as to what you want.


tedd
--
---
http://sperling.com  http://ancientstones.com  http://earthstones.com

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting MySQL queries

2006-11-06 Thread Curt Zirzow

On 11/5/06, Roman Neuhauser [EMAIL PROTECTED] wrote:


If you used PostgreSQL I'd suggest a functional index and ordering
on the function... Does MySQL have anything like this?

CREATE FUNCTION fn(TEXT)
RETURNS TEXT
IMMUTABLE STRICT
LANGUAGE SQL
AS $$
  SELECT regexp_replace($1, '^(?:(?:a|the)[[:space:]]+)', '', 'i');
$$;

CREATE INDEX ON table(fn(subject));


Thats rather nifty, i dont think you can do that with mysql, but you
could achieve something close to that with a trigger for insert/update
to apply the regex to a different field that is used for sorting.

The other option would make a policy to put , The or , A at the
end of the string a simple function to render the text without the
comma at the end would be simple to do.

Curt

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting MySQL queries

2006-11-06 Thread Richard Lynch
On Sun, November 5, 2006 7:13 am, Dotan Cohen wrote:
 I have a list of subjects, such as Linux, Open Source, and the
 World Wide Web. The subjects are stored in a database and being
 retrieved via php. I currently organize them alphabetically with SQL's
 ORDER BY ASC argument, however, if there is a preceding the  or a 
 then that is considered as part of the alphabetical order. Thus, all
 the subjects starting with the  are grouped together, as are the
 subjects starting with a . How can I order by ascending, without
 taking the preceding the  or a  into account?

 ** Example:
 Now, the list is ordeded like this:
 a Distribution
 a Text Editor
 a Virus
 Bluetooth
 Copyleft
 DRM
 Fedora
 Firefox

 However, I'd like it to be ordered like this:
 Bluetooth
 Copyleft
 a Distribution
 DRM
 Fedora
 Firefox
 a Text Editor
 a Virus

 Current code:
 $query  = SELECT subject FROM table ORDER BY subject asc;
 $result = mysql_query($query);

I forget the SQL 'CASE' syntax, but it goes something like this:
$query = SELECT subject, case when substring(lower(subject, 0, 4) =
'the ') then substring(subject, 4)  when substring(lower(subject, 0,
3) = 'an ' then substring(subject, 3) when substring(lower(subject, 0,
2) = 'a ') then substring(subject, 2) else subject) as subject_alpha
FROM table ORDER BY subject_alpha;

'Course, that renders ineffective any index you got on 'subject',
almost for sure.

If the table is HUGE and/or performance is an issue, you could set up
a second field called subject_alpha which holds the alphabetized
version.

Then you need to be sure it's always kept in sync by your application.

Or triggers and all that in later MySQL.

Actually, super-recent MySQL has user-defined functions, I think, so
the previous solution by another post may be better in that case.

I do not think there is a magic built-in easy MySQL function for this,
though you never know unless you read MySQL docs and ask on the MySQL
mailing list.  (Hint, hint.)

-- 
Some people have a gift link here.
Know what I want?
I want you to buy a CD from some starving artist.
http://cdbaby.com/browse/from/lynch
Yeah, I get a buck. So?

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting MySQL queries

2006-11-06 Thread Dotan Cohen

On 06/11/06, Richard Lynch [EMAIL PROTECTED] wrote:

On Sun, November 5, 2006 7:13 am, Dotan Cohen wrote:
 I have a list of subjects, such as Linux, Open Source, and the
 World Wide Web. The subjects are stored in a database and being
 retrieved via php. I currently organize them alphabetically with SQL's
 ORDER BY ASC argument, however, if there is a preceding the  or a 
 then that is considered as part of the alphabetical order. Thus, all
 the subjects starting with the  are grouped together, as are the
 subjects starting with a . How can I order by ascending, without
 taking the preceding the  or a  into account?

 ** Example:
 Now, the list is ordeded like this:
 a Distribution
 a Text Editor
 a Virus
 Bluetooth
 Copyleft
 DRM
 Fedora
 Firefox

 However, I'd like it to be ordered like this:
 Bluetooth
 Copyleft
 a Distribution
 DRM
 Fedora
 Firefox
 a Text Editor
 a Virus

 Current code:
 $query  = SELECT subject FROM table ORDER BY subject asc;
 $result = mysql_query($query);

I forget the SQL 'CASE' syntax, but it goes something like this:
$query = SELECT subject, case when substring(lower(subject, 0, 4) =
'the ') then substring(subject, 4)  when substring(lower(subject, 0,
3) = 'an ' then substring(subject, 3) when substring(lower(subject, 0,
2) = 'a ') then substring(subject, 2) else subject) as subject_alpha
FROM table ORDER BY subject_alpha;

'Course, that renders ineffective any index you got on 'subject',
almost for sure.

If the table is HUGE and/or performance is an issue, you could set up
a second field called subject_alpha which holds the alphabetized
version.

Then you need to be sure it's always kept in sync by your application.

Or triggers and all that in later MySQL.

Actually, super-recent MySQL has user-defined functions, I think, so
the previous solution by another post may be better in that case.

I do not think there is a magic built-in easy MySQL function for this,
though you never know unless you read MySQL docs and ask on the MySQL
mailing list.  (Hint, hint.)



I just subscribed back to the MySQL list (unsubscribed a few months
ago) to ask the question. If there's no super-smart way to do it, then
I'll use the pseudo-subject field and sort on it. Performance-wise, I
agree that it can't be beat.

Thanks.

Dotan Cohen

http://lyricslist.com/
http://what-is-what.com/what_is/xml.html

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting MySQL queries

2006-11-06 Thread Børge Holen
On Monday 06 November 2006 08:15, clive wrote:
  Current code:
  $query  = SELECT subject FROM table ORDER BY subject asc;
  $result = mysql_query($query);

 I dont seen any php code to do any sorting,just a mysql query, perhaps a
 mysql list or maybe you should try doing it in php yourself first.

 Not that I know the answer, but mysql does have a substring function,
 perhaps it can help.

substring is quite powerful. Never tried one of those though

-- 
---
Børge
Kennel Arivene 
http://www.arivene.net
---

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting MySQL queries

2006-11-05 Thread Roman Neuhauser
# [EMAIL PROTECTED] / 2006-11-05 15:13:19 +0200:
 I have a list of subjects, such as Linux, Open Source, and the
 World Wide Web. The subjects are stored in a database and being
 retrieved via php. I currently organize them alphabetically with SQL's
 ORDER BY ASC argument, however, if there is a preceding the  or a 
 then that is considered as part of the alphabetical order. Thus, all
 the subjects starting with the  are grouped together, as are the
 subjects starting with a . How can I order by ascending, without
 taking the preceding the  or a  into account?

 Current code:
 $query  = SELECT subject FROM table ORDER BY subject asc;
 $result = mysql_query($query);

If you used PostgreSQL I'd suggest a functional index and ordering
on the function... Does MySQL have anything like this?

CREATE FUNCTION fn(TEXT)
RETURNS TEXT
IMMUTABLE STRICT
LANGUAGE SQL
AS $$
  SELECT regexp_replace($1, '^(?:(?:a|the)[[:space:]]+)', '', 'i');
$$;

CREATE INDEX ON table(fn(subject));

SELECT subject FROM table ORDER BY fn(subject) ASC;

-- 
How many Vietnam vets does it take to screw in a light bulb?
You don't know, man.  You don't KNOW.
Cause you weren't THERE. http://bash.org/?255991

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting MySQL queries

2006-11-05 Thread clive


Current code:
$query  = SELECT subject FROM table ORDER BY subject asc;
$result = mysql_query($query);


I dont seen any php code to do any sorting,just a mysql query, perhaps a 
mysql list or maybe you should try doing it in php yourself first.


Not that I know the answer, but mysql does have a substring function, 
perhaps it can help.


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting Multidimensional Array

2006-10-31 Thread Richard Lynch
On Tue, October 31, 2006 11:10 am, Keith Spiller wrote:
 RE:  Sorting Multidimensional Array

 I'm trying to sort a multidimensional array.  The data was taken from
 a mysql query:

 $myrow = mysql_fetch_row($result) {
   query[] = $myrow;
 }

 The purpose is to retrieve the table data and manually add a record,
 then sort ASC by the startdate which is the forth field...

 Something like:

 $test = array_multisort($query, $key = '$query[4]');

 Any help would be greatly appreciated.  Thanks,

Don't do that. :-)

For starters, sorting in PHP is MUCH less efficient than in a DB.

Secondly, getting multi-dimensional (sic) arrays in PHP to sort like
you want generates a ton of traffic here, so it must be hard. :-)

You can do somethig like this:

(SELECT x, y, z FROM real_data
 UNION
 SELECT 'manually', 'inserted', 'data' as z
)
ORDER BY z

And achieve MUCH better results with far less headache.

If 'z' is indexed in real_data, add another ORDER BY z right before
the UNION -- That will probably make it very fast/easy for the DB to
splice in your manually-inserted 'z' value.

-- 
Some people have a gift link here.
Know what I want?
I want you to buy a CD from some starving artist.
http://cdbaby.com/browse/from/lynch
Yeah, I get a buck. So?

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting Multidimensional Array

2006-10-31 Thread Keith Spiller

Thanks Richard,

But wouldn't order by z interfere with my original order by values?

My code is as follows:

  $fields1  =  ID, Title, Label, Location, Start, End, Time, ;
  $fields1 .=  Description, Organization, Department, Contact, ;
  $fields1 .=  Phone, Email, Global, Board, Committee, Status, TBD_Time ;

  $command  =  SELECT $fields1, TO_DAYS(End) - TO_DAYS(Start) + 1 AS Days 
;

  $command .=  FROM $tablename ;
  $command .=  $WHERETXT ORDER BY $sortby $sortorder ;


I just need to add a new record, but I have to use PHP because the Start and 
End

dates for that record must match the current month...

If I could add the record to the Select statement as you suggest that would 
be wonderful.



Keith


- Original Message - 
From: Richard Lynch [EMAIL PROTECTED]

To: Keith Spiller [EMAIL PROTECTED]
Cc: php-general@lists.php.net
Sent: Tuesday, October 31, 2006 10:48 AM
Subject: Re: [PHP] Sorting Multidimensional Array



On Tue, October 31, 2006 11:10 am, Keith Spiller wrote:

RE:  Sorting Multidimensional Array

I'm trying to sort a multidimensional array.  The data was taken from
a mysql query:

$myrow = mysql_fetch_row($result) {
  query[] = $myrow;
}

The purpose is to retrieve the table data and manually add a record,
then sort ASC by the startdate which is the forth field...

Something like:

$test = array_multisort($query, $key = '$query[4]');

Any help would be greatly appreciated.  Thanks,


Don't do that. :-)

For starters, sorting in PHP is MUCH less efficient than in a DB.

Secondly, getting multi-dimensional (sic) arrays in PHP to sort like
you want generates a ton of traffic here, so it must be hard. :-)

You can do somethig like this:

(SELECT x, y, z FROM real_data
UNION
SELECT 'manually', 'inserted', 'data' as z
)
ORDER BY z

And achieve MUCH better results with far less headache.

If 'z' is indexed in real_data, add another ORDER BY z right before
the UNION -- That will probably make it very fast/easy for the DB to
splice in your manually-inserted 'z' value.

--
Some people have a gift link here.
Know what I want?
I want you to buy a CD from some starving artist.
http://cdbaby.com/browse/from/lynch
Yeah, I get a buck. So? 


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting array after array_count_values

2006-08-15 Thread Richard Lynch
On Tue, August 15, 2006 9:01 am, [EMAIL PROTECTED] wrote:
 I have an array of products $products
 $products = array_count_values($products);
 now I have an array where $key is product number and $value is how
 many
 times I have such a product in the array.
 I want to sort this new array that product with the most duplicates
 are
 on the first place, but what ever I use (rsort, krsort,..) i loose
 product
 numbers (key).

http://php.net/asort

-- 
Like Music?
http://l-i-e.com/artists.htm

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting in array

2006-08-03 Thread Richard Lynch
For starters, the function is supposed to return 0 for countries that
are equal.

As it stands now, it's going to return 1 / -1 randomly based on which
arg happens to be $a versus $b.

That's bad.

For some implementations of shuffle/sort routines, it will actually
crash.

I forget which implementation does this, but it's got to do with
caching the comparison result in a B-tree and then walking the tree
assuming that the comparison will be consistent...

Anyway, as far as doesn't work goes, you'd have to give us more info
about how it's not working...

On Mon, July 31, 2006 1:56 am, weetat wrote:

 Hi ,

Doesn't work .
Any ideas ?

 Thanks
 Peter Lauri wrote:
function cmpcountry($a, $b)
{

  $country1 = $a['country'];
  $country2 = $b['country'];

 if($country1=='') return 1;
 else return ($country1  $country2) ? -1 : 1;

}

 -Original Message-
 From: weetat [mailto:[EMAIL PROTECTED]
 Sent: Monday, July 31, 2006 12:32 PM
 To: php-general@lists.php.net
 Subject: [PHP] sorting in array

 Hi all ,

   I have array value as shown below, i have paste my test php code
 below:
   I have problem when doing usort() when 'country' = '', i would
 like to
 display records where country = '' last. Any ideas how to do that ?

 Thanks

$arraytest= array(
   array
  (
  'country' = '',
  )
   ,
   array
  (
  'country' = 'Thailand',
  )
   ,
   array
  (
  'country' = 'Singapore',
  )
   ,
   array
  (
  'country' = 'Singapore',
  )
   ,
   array
  (
  'country' = '',
  )
,
array
  (
  'country' = '',
  )
  ,
  array
  (
  'country' = '',
  )

   );


function cmpcountry($a, $b)
{

  $country1 = $a['country'];
  $country2 = $b['country'];

   return ($country1  $country2) ? -1 : 1;
}

  usort($arraytest,cmpcountry);
  while(list($name,$value)=each($arraytest)){
 echo $name.brbr;

 while(list($n,$v) = each($arraytest[$name])){
 echo $v.brbr;
 }
   }


 --
 PHP General Mailing List (http://www.php.net/)
 To unsubscribe, visit: http://www.php.net/unsub.php




-- 
Like Music?
http://l-i-e.com/artists.htm

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting in array

2006-07-31 Thread weetat


Hi ,

  Doesn't work .
  Any ideas ?

Thanks
Peter Lauri wrote:

   function cmpcountry($a, $b)
   {

 $country1 = $a['country'];
 $country2 = $b['country'];

   if($country1=='') return 1;
   else return ($country1  $country2) ? -1 : 1;

   }

-Original Message-
From: weetat [mailto:[EMAIL PROTECTED] 
Sent: Monday, July 31, 2006 12:32 PM

To: php-general@lists.php.net
Subject: [PHP] sorting in array

Hi all ,

  I have array value as shown below, i have paste my test php code below:
  I have problem when doing usort() when 'country' = '', i would like to 
display records where country = '' last. Any ideas how to do that ?


Thanks

   $arraytest= array(
  array
 (
 'country' = '',
 )
  ,
  array
 (
 'country' = 'Thailand',
 )
  ,
  array
 (
 'country' = 'Singapore',
 )
  ,
  array
 (
 'country' = 'Singapore',
 )
  ,
  array
 (
 'country' = '',
 )
   ,
  array
 (
 'country' = '',
 )
,
array
 (
 'country' = '',
 )

  );


   function cmpcountry($a, $b)
   {

 $country1 = $a['country'];
 $country2 = $b['country'];

  return ($country1  $country2) ? -1 : 1;
   }

 usort($arraytest,cmpcountry);
 while(list($name,$value)=each($arraytest)){
   echo $name.brbr;

   while(list($n,$v) = each($arraytest[$name])){
   echo $v.brbr;
   }
  }



--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting in array

2006-07-31 Thread Paul Novitski

At 10:31 PM 7/30/2006, weetat wrote:
 I have problem when doing usort() when 'country' = '', i would 
like to display records where country = '' last. Any ideas how to do that ?

...

  $arraytest= array(
 array
(
'country' = '',
)
 ,
 array
(
'country' = 'Thailand',
)

...

  function cmpcountry($a, $b)
  {
$country1 = $a['country'];
$country2 = $b['country'];

 return ($country1  $country2) ? -1 : 1;
  }



Weetat,

You can sort the blank fields to the end simply by forcing their 
evaluated values in your usort callback function:


  function cmpcountry($a, $b)
  {
$country1 = $a['country'];
$country2 = $b['country'];

if ($country1 == '') $country1 = zzz;
if ($country2 == '') $country2 = zzz;

return ($country1  $country2) ? -1 : 1;
  }

...or, using ternary syntax:

  function cmpcountry($a, $b)
  {
$country1 = ($a['country'] == '') ? zzz : $a['country'];
$country2 = ($b['country'] == '') ? zzz : $b['country'];

return ($country1  $country2) ? -1 : 1;
  }


Regards,
Paul 


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] sorting in array

2006-07-31 Thread Paul Novitski

At 05:40 PM 7/30/2006, Peter Lauri wrote:

   function cmpcountry($a, $b)
   {

 $country1 = $a['country'];
 $country2 = $b['country'];

   if($country1=='') return 1;
   else return ($country1  $country2) ? -1 : 1;

   }



Good call, Peter; my suggestion was unnecessarily fat.

Weetat, both Peter's and my solutions do work -- see here:
http://juniperwebcraft.com/test/sortTest.php
source code:
http://juniperwebcraft.com/test/sortTest.txt

I could make that last statement just a bit simpler:

  function cmpcountry($a, $b)
  {
$country1 = ($a['country'] == '') ? zzz : $a['country'];
$country2 = ($b['country'] == '') ? zzz : $b['country'];

return ($country1  ''  $country1  $country2) ? -1 : 1;
  }

I'm curious to know why none of this code works properly if it 
directly compares ($a['country']  $b['country']).  Why are the 
intermediate variables necessary?


Paul 


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] sorting in array

2006-07-31 Thread Paul Novitski

At 12:22 AM 7/31/2006, Paul Novitski wrote:

I could make that last statement just a bit simpler:

  function cmpcountry($a, $b)
  {
$country1 = ($a['country'] == '') ? zzz : $a['country'];
$country2 = ($b['country'] == '') ? zzz : $b['country'];

return ($country1  ''  $country1  $country2) ? -1 : 1;
  }



*Sigh*  I shouldn't post this late at night.  This is the comparison 
function that works for me:


  function cmpcountry($a, $b)
  {
$country1 = ($a['country'] == '') ? zzz : $a['country'];
$country2 = ($b['country'] == '') ? zzz : $b['country'];

return ($country1  $country2) ? -1 : 1;
  }

demo: http://juniperwebcraft.com/test/sortTest.php
code: http://juniperwebcraft.com/test/sortTest.txt

Paul  


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting in array

2006-07-31 Thread weetat

Thanks Paul,

  Very weird tried Peter's option, it doesn't work.

  Btw , how to sort by ascending ?

Thanks

Paul Novitski wrote:

At 12:22 AM 7/31/2006, Paul Novitski wrote:

I could make that last statement just a bit simpler:

  function cmpcountry($a, $b)
  {
$country1 = ($a['country'] == '') ? zzz : $a['country'];
$country2 = ($b['country'] == '') ? zzz : $b['country'];

return ($country1  ''  $country1  $country2) ? -1 : 1;
  }



*Sigh*  I shouldn't post this late at night.  This is the comparison 
function that works for me:


  function cmpcountry($a, $b)
  {
$country1 = ($a['country'] == '') ? zzz : $a['country'];
$country2 = ($b['country'] == '') ? zzz : $b['country'];

return ($country1  $country2) ? -1 : 1;
  }

demo: http://juniperwebcraft.com/test/sortTest.php
code: http://juniperwebcraft.com/test/sortTest.txt

Paul 


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting in array

2006-07-31 Thread Paul Novitski

At 01:14 AM 7/31/2006, weetat wrote:

Thanks Paul,

  Very weird tried Peter's option, it doesn't work.

  Btw , how to sort by ascending ?



Please explain what you mean.  The current script DOES sort ascending 
by country (except for the blank country fields which are placed at the end):

http://juniperwebcraft.com/test/sortTest.php

Singapore, Singapore, Thailand is an ascending sort.

Your original code also sorted ascending by country, but with the 
blank countries at the front:


  function cmpcountry($a, $b)
  {
$country1 = $a['country'];
$country2 = $b['country'];

return ($country1  $country2) ? -1 : 1;
  }

Paul 


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] sorting in array

2006-07-31 Thread Peter Lauri
And this for DESCending

   function cmpcountry($a, $b)
   {
 $country1 = $a['country'];
 $country2 = $b['country'];

if($country1=='' OR $country2=='') {
if($country1==$country2) return 0;
elseif($country1=='') return 1;
else return -1;
} else return ($country1  $country2) ? 1 : -1;
   }

-Original Message-
From: weetat [mailto:[EMAIL PROTECTED] 
Sent: Monday, July 31, 2006 3:15 PM
To: php-general@lists.php.net; Paul Novitski
Cc: php-general@lists.php.net
Subject: Re: [PHP] sorting in array

Thanks Paul,

   Very weird tried Peter's option, it doesn't work.

   Btw , how to sort by ascending ?

Thanks

Paul Novitski wrote:
 At 12:22 AM 7/31/2006, Paul Novitski wrote:
 I could make that last statement just a bit simpler:

   function cmpcountry($a, $b)
   {
 $country1 = ($a['country'] == '') ? zzz : $a['country'];
 $country2 = ($b['country'] == '') ? zzz : $b['country'];

 return ($country1  ''  $country1  $country2) ? -1 : 1;
   }
 
 
 *Sigh*  I shouldn't post this late at night.  This is the comparison 
 function that works for me:
 
   function cmpcountry($a, $b)
   {
 $country1 = ($a['country'] == '') ? zzz : $a['country'];
 $country2 = ($b['country'] == '') ? zzz : $b['country'];
 
 return ($country1  $country2) ? -1 : 1;
   }
 
 demo: http://juniperwebcraft.com/test/sortTest.php
 code: http://juniperwebcraft.com/test/sortTest.txt
 
 Paul 

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] sorting in array

2006-07-31 Thread Peter Lauri
Sorry, I just woke up and just posted an reply without thinking, use this:

   function cmpcountry($a, $b)
   {
 $country1 = $a['country'];
 $country2 = $b['country'];

if($country1=='' OR $country2=='') {
if($country1==$country2) return 0;
elseif($country1=='') return 1;
else return -1;
} else return ($country1  $country2) ? -1 : 1;
   }

/Peter



-Original Message-
From: Paul Novitski [mailto:[EMAIL PROTECTED] 
Sent: Monday, July 31, 2006 1:57 PM
To: php-general@lists.php.net
Subject: Re: [PHP] sorting in array

At 10:31 PM 7/30/2006, weetat wrote:
  I have problem when doing usort() when 'country' = '', i would 
 like to display records where country = '' last. Any ideas how to do that
?
...
   $arraytest= array(
  array
 (
 'country' = '',
 )
  ,
  array
 (
 'country' = 'Thailand',
 )
...
   function cmpcountry($a, $b)
   {
 $country1 = $a['country'];
 $country2 = $b['country'];

  return ($country1  $country2) ? -1 : 1;
   }


Weetat,

You can sort the blank fields to the end simply by forcing their 
evaluated values in your usort callback function:

   function cmpcountry($a, $b)
   {
 $country1 = $a['country'];
 $country2 = $b['country'];

 if ($country1 == '') $country1 = zzz;
 if ($country2 == '') $country2 = zzz;

 return ($country1  $country2) ? -1 : 1;
   }

...or, using ternary syntax:

   function cmpcountry($a, $b)
   {
 $country1 = ($a['country'] == '') ? zzz : $a['country'];
 $country2 = ($b['country'] == '') ? zzz : $b['country'];

 return ($country1  $country2) ? -1 : 1;
   }


Regards,
Paul 

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting in array

2006-07-31 Thread David Tulloh
weetat wrote:
 Hi all ,
 
  I have array value as shown below, i have paste my test php code below:
  I have problem when doing usort() when 'country' = '', i would like to
 display records where country = '' last. Any ideas how to do that ?
 ...

You might try searching the list's archive's.  This question has been
asked and answered several times before.

http://aspn.activestate.com/ASPN/Mail/Message/php-general/3172783
http://aspn.activestate.com/ASPN/Mail/Message/php-general/3199536
http://aspn.activestate.com/ASPN/Mail/Message/php-general/3212898

one of the solutions offered:
http://aspn.activestate.com/ASPN/Mail/Message/3172873

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] sorting in array

2006-07-30 Thread Peter Lauri
   function cmpcountry($a, $b)
   {

 $country1 = $a['country'];
 $country2 = $b['country'];

   if($country1=='') return 1;
   else return ($country1  $country2) ? -1 : 1;

   }

-Original Message-
From: weetat [mailto:[EMAIL PROTECTED] 
Sent: Monday, July 31, 2006 12:32 PM
To: php-general@lists.php.net
Subject: [PHP] sorting in array

Hi all ,

  I have array value as shown below, i have paste my test php code below:
  I have problem when doing usort() when 'country' = '', i would like to 
display records where country = '' last. Any ideas how to do that ?

Thanks

   $arraytest= array(
  array
 (
 'country' = '',
 )
  ,
  array
 (
 'country' = 'Thailand',
 )
  ,
  array
 (
 'country' = 'Singapore',
 )
  ,
  array
 (
 'country' = 'Singapore',
 )
  ,
  array
 (
 'country' = '',
 )
   ,
  array
 (
 'country' = '',
 )
,
array
 (
 'country' = '',
 )

  );


   function cmpcountry($a, $b)
   {

 $country1 = $a['country'];
 $country2 = $b['country'];

  return ($country1  $country2) ? -1 : 1;
   }

 usort($arraytest,cmpcountry);
 while(list($name,$value)=each($arraytest)){
   echo $name.brbr;

   while(list($n,$v) = each($arraytest[$name])){
   echo $v.brbr;
   }
  }

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting array question

2006-07-26 Thread John Wells

On 7/26/06, Angelo Zanetti [EMAIL PROTECTED] wrote:

Hi all,
So they way I want to sort these rows is by total, totalPaid,
totalUnpaid all descending.


Hi Angelo,

So the first question the list will ask is if the array of data is
coming from a database.  Because then you'd be urged to perform the
sorting from within your database query.

Barring that, you can use the usort() function to create custom
sorting.  What I've done below should do what you want, and I've tried
to generalize the functions a bit, so that you can mix descending and
ascending as you wish:

[code]
// Basic function for comparing arrays based on a particular column
function compareColumn($x, $y, $idx, $lessThan, $greaterThan)
{
if ( $x[$idx] == $y[$idx] )
 return 0;
else if ( $x[$idx]  $y[$idx] )
 return $lessThan;
else
 return $greaterThan;
}

// Calls compareColumn so that it sorts in descending order
function compareColumnDesc($x, $y, $idx)
{
return compareColumn($x, $y, $idx, 1, -1);
}

// Calls compareColumn so that it sorts in ascending order
function compareColumnAsc($x, $y, $idx)
{
return compareColumn($x, $y, $idx, -1, 1);
}

// Your customer comparison function.  The order in which you call each
// compareColumn*() is the ultimate order in which your multi-dim
array is sorted.
function compare($x, $y)
{
// total is index 2 of the array
$total = compareColumnDesc($x, $y, 2);
if($total != 0) return $total;

// totalPaid is index 3 of the array
$totalPaid = compareColumnDesc($x, $y, 3);
if($totalPaid != 0) return $totalPaid;

// totalUnpaid is index 4 of the array
$totalUnpaid = compareColumnDesc($x, $y, 4);
if($totalUnpaid != 0) return $totalUnpaid;

// arrays were equal
return 0;
}

$record = array(
array(1, 'marc', 12, 5, 7),
array(5, 'berty', 30, 12, 18),
array(7, 'sarah', 19, 12, 7)
);

// sort your array
usort($record, 'compare');

// print sorted array
echo 'pre';
var_export($record);
echo '/pre';
[/code]


HTH,
John W

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting array question

2006-07-26 Thread Angelo Zanetti

hi guys,

thanks for the replies! yes Melanie, you were correct the last example 
(i had an old version of the manual). seemed to do the trick =)


Thanks to john as well for the reply.

Angelo

Melanie Maddix wrote:


[snip]
So they way I want to sort these rows is by total, totalPaid, 
totalUnpaid all descending.

Output should be:
partnerID  | partnerName | total  | totalPaid  | totalUnpaid
5  berty   301218
7  sarah   19127
1  marc   12  57




I have looked at the manual and found uasort and array_multisort, but 
these don't seem to be appropriate unless Im missing something but the 
examples found are very vague.

If anyone can help that would be great,

Thanks in advance
Angelo
[/snip]


Hi Angelo,

Take a look at Example 3 under array_multisort, the one that sorts by
volume and edition. 


You first build arrays of the columns you want to sort by, then pass
them as an argument to array_multisort, along with your original array.

Melanie

 



--

Angelo Zanetti
Systems developer


*Telephone:* +27 (021) 469 1052
*Mobile:*   +27 (0) 72 441 3355
*Fax:*+27 (0) 86 681 5885
*
Web:* http://www.zlogic.co.za
*E-Mail:* [EMAIL PROTECTED] mailto:[EMAIL PROTECTED]

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting troubles

2006-04-25 Thread Richard Lynch
On Sat, April 22, 2006 4:49 am, William Stokes wrote:
 I have a column in DB that contains this kind of data,
 A20,B16,B17C14,C15,D13,D12 etc.

 I would like to print this data to a page and sort it ascending by the
 letter an descending by the number. Can this be done? Like

 A20
 B17
 B16
 C15
 C14
 D13
 D12

I personally would do it in SQL, since SQL has been specifically
fine-tuned for about 4 decades to do this [bleep] fast, while PHP has
not:

select col from DB order by substring(col, 1, 1), substring(col, 2)

You could also consider creating a view in your DB, if your DB
supports views.

If not, and the dataset is VERY large, and/or your particular database
does not allow a function in ORDER BY clauses, I would suggest you add
two indexed fields and break that one column up into two.

You'd need to add some kind of logic somewhere (triggers in the DB,
application logic, whatever) to manage the copying of the data from
the column to the other.

No matter how you slice it, though, the LAST option I'd use would be
to use http://php.net/usort to sort the data from a DB in PHP.  Still,
it's an option, if your DB is particularly broken, to the point where
none of the above apply. I don't think any such DB exists with PHP
support, unless maybe via ODBC, but I may as well provide the complete
answer, eh?

-- 
Like Music?
http://l-i-e.com/artists.htm

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting troubles

2006-04-25 Thread William Stokes
Thanks for your input everyone!
The easiest way to do this was ansding this to the SELECT clause:

select col from DB order by substring(col, 1, 1) ASC, substring(col, 2) DESC

Seems to work fine.
-Will


Richard Lynch [EMAIL PROTECTED] kirjoitti 
viestissä:[EMAIL PROTECTED]
 On Sat, April 22, 2006 4:49 am, William Stokes wrote:
 I have a column in DB that contains this kind of data,
 A20,B16,B17C14,C15,D13,D12 etc.

 I would like to print this data to a page and sort it ascending by the
 letter an descending by the number. Can this be done? Like

 A20
 B17
 B16
 C15
 C14
 D13
 D12

 I personally would do it in SQL, since SQL has been specifically
 fine-tuned for about 4 decades to do this [bleep] fast, while PHP has
 not:

 select col from DB order by substring(col, 1, 1), substring(col, 2)

 You could also consider creating a view in your DB, if your DB
 supports views.

 If not, and the dataset is VERY large, and/or your particular database
 does not allow a function in ORDER BY clauses, I would suggest you add
 two indexed fields and break that one column up into two.

 You'd need to add some kind of logic somewhere (triggers in the DB,
 application logic, whatever) to manage the copying of the data from
 the column to the other.

 No matter how you slice it, though, the LAST option I'd use would be
 to use http://php.net/usort to sort the data from a DB in PHP.  Still,
 it's an option, if your DB is particularly broken, to the point where
 none of the above apply. I don't think any such DB exists with PHP
 support, unless maybe via ODBC, but I may as well provide the complete
 answer, eh?

 -- 
 Like Music?
 http://l-i-e.com/artists.htm 

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting troubles

2006-04-24 Thread Philip Thompson

On Apr 22, 2006, at 4:49 AM, William Stokes wrote:


Hello,

Any idea how to sort this?

I have a column in DB that contains this kind of data,
A20,B16,B17C14,C15,D13,D12 etc.

I would like to print this data to a page and sort it ascending by the
letter an descending by the number. Can this be done? Like

A20
B17
B16
C15
C14
D13
D12

Thanks
-Will


Maybe I'm missing something, but I don't think that I've seen anyone  
mention this. Can you not just sort the data before it reaches your  
php code... meaning, via the db? My example uses MySQL:


?
$result = msyql_query(SELECT * FROM your_database ORDER BY ASC,  
$link);


while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
  $column[$i++] = $row[your_column];

...

for ($i=0; $i$numOfCols; $i++)
  echo $column[$i]br/;
?

Again, I may have misread what you are asking, but this appears to be  
a simple solution when pulling from a database.


Good luck,
~Philip

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting troubles

2006-04-24 Thread Philip Thompson

On Apr 24, 2006, at 9:06 AM, Philip Thompson wrote:


On Apr 22, 2006, at 4:49 AM, William Stokes wrote:


Hello,

Any idea how to sort this?

I have a column in DB that contains this kind of data,
A20,B16,B17C14,C15,D13,D12 etc.

I would like to print this data to a page and sort it ascending by  
the

letter an descending by the number. Can this be done? Like

A20
B17
B16
C15
C14
D13
D12

Thanks
-Will


Maybe I'm missing something, but I don't think that I've seen  
anyone mention this. Can you not just sort the data before it  
reaches your php code... meaning, via the db? My example uses MySQL:


?
$result = msyql_query(SELECT * FROM your_database ORDER BY ASC,  
$link);


Ooops!

... ORDER BY your_column ASC ...



while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
  $column[$i++] = $row[your_column];

...

for ($i=0; $i$numOfCols; $i++)
  echo $column[$i]br/;
?

Again, I may have misread what you are asking, but this appears to  
be a simple solution when pulling from a database.


Good luck,
~Philip


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting troubles

2006-04-23 Thread chris smith
 I have a column in DB that contains this kind of data,
 A20,B16,B17C14,C15,D13,D12 etc.

 I would like to print this data to a page and sort it ascending by the
 letter an descending by the number. Can this be done? Like

 A20
 B17
 B16
 C15
 C14
 D13
 D12

Depending on how many records you have and how many you want per page,
you might be better off doing this in your database query (eg you have
d01 - d99 and only want to show 30 per page)...

Depending on which db you use, different syntaxes will apply.. so if
you need further help send which db and which version.

--
Postgresql  php tutorials
http://www.designmagick.com/

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting troubles

2006-04-23 Thread David Tulloh
William Stokes wrote:
 Hello,
 
 Any idea how to sort this?
 
 I have a column in DB that contains this kind of data, 
 A20,B16,B17C14,C15,D13,D12 etc.
 
 I would like to print this data to a page and sort it ascending by the 
 letter an descending by the number. Can this be done? 

PHP has the usort() function which allows you to sort by another
function.  This allows you to very neatly sort by virtually any criteria.

I knocked up a fairly simple function to do the sort that you described.
The format for the comparison function is in the usort() documentation
as well as several examples.

php
function weird_comparison($a, $b) {
# return -1, 0, 1 if $a is less than, equal to or greater than $b
if($a{0}  $b{0})
return 1;
elseif($a{0}  $b{0})
return -1;
else {
$a_num = substr($a, 1);
$b_num = substr($b, 1);
if($a_num  $b_num)
return -1;
elseif($a_num  $b_num)
return 1;
else
return 0;
}
}

$arr = explode(',', 'A20,B16,B17,C14,C15,D13,D12');
print_r($arr);
usort($arr, 'weird_comparison');
print_r($arr);
?


David

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting troubles

2006-04-22 Thread Peter Hoskin
See explode, http://www.php.net/explode

$var = 'A20,B16,B17C14,C15,D13,D12';
$array = explode(',',$var);

foreach ($array as $key = $value) {
  echo $value .\n;
}


William Stokes wrote:
 Hello,

 Any idea how to sort this?

 I have a column in DB that contains this kind of data, 
 A20,B16,B17C14,C15,D13,D12 etc.

 I would like to print this data to a page and sort it ascending by the 
 letter an descending by the number. Can this be done? Like

 A20
 B17
 B16
 C15
 C14
 D13
 D12

 Thanks
 -Will 

   

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting troubles

2006-04-22 Thread Peter Hoskin
hmm, should also see http://www.php.net/sort

Peter Hoskin wrote:
 See explode, http://www.php.net/explode

 $var = 'A20,B16,B17C14,C15,D13,D12';
 $array = explode(',',$var);

 foreach ($array as $key = $value) {
   echo $value .\n;
 }


 William Stokes wrote:
   
 Hello,

 Any idea how to sort this?

 I have a column in DB that contains this kind of data, 
 A20,B16,B17C14,C15,D13,D12 etc.

 I would like to print this data to a page and sort it ascending by the 
 letter an descending by the number. Can this be done? Like

 A20
 B17
 B16
 C15
 C14
 D13
 D12

 Thanks
 -Will 

   
 

   

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting troubles

2006-04-22 Thread Paul Novitski

At 02:49 AM 4/22/2006, William Stokes wrote:

I have a column in DB that contains this kind of data,
A20,B16,B17C14,C15,D13,D12 etc.

I would like to print this data to a page and sort it ascending by the
letter an descending by the number. Can this be done? Like

A20
B17
B16
C15
C14
D13
D12



Will, I can think of two ways to do this.

One way involves splitting each value into its two components so you 
can sort one ASC  the other DESC.


(First off, I'd seriously consider storing them in two separate DB 
fields.  If you can do this, your problem is over because you can 
extract them in a query in just the order you want.  If you're 
sorting them in opposite directions that's a pretty good clue that 
they're really separate data and should be stored separately.)


But you can split them on the fly in PHP.  You can run preg_match() 
on each element of your array with a RegExp something like:


/(\D)(\d+)/

(one non-numeric character followed by one or more numeric digits)

preg_match(/(\D)(\d+)/, $aData($i), $aMatches)

is going to produce an array like:

$aMatches = array(
[0] = A20
[1] = A
[2] = 20
)

Build a workspace array using those three match values, sort the way 
you want on [1]  [2], and extract your result array from [0].



An alternative way to do this, trickier but probably much faster, is 
to translate the initial letter into a value that's its inverse:


$aFrom = array(A,B,C,...Z);
$aTo = array(Z,Y,X,...A);

$aTemp = str_replace($aFrom, $aTo, $aData);

This will translate the letters in all the elements of the data array 
into their inverse:


B16 -- Y16
A20 -- Z20
B17 -- Y17
...

Then just do a reverse sort on $aTemp and you get:

Z20
Y17
Y16

Then translate the letters back to their original values and you get:

A20
B17
C16

Voila.

Paul 


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting troubles

2006-04-22 Thread Paul Novitski

At 03:43 AM 4/22/2006, I wrote:

Then just do a reverse sort on $aTemp and you get:

Z20
Y17
Y16

Then translate the letters back to their original values and you get:

A20
B17
C16



Oops, I made a typo: that final value should have been B16, not C16.

(All the same, not too shabby for four in the morning...)

Paul 


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting dates with php

2005-12-21 Thread André Medeiros
You COULD sort them if the date was stored backwards, ie. Year/Month/Day

On 12/21/05, Jim Moseby [EMAIL PROTECTED] wrote:
  Have a load of dates in the format DD/MM/YY. Thet are stored
  as a VARCHAR on
  a mysql DB.
 
  I need a way to sort them into order(most recent first)
 
 
  Using the QUERY   $query = SELECT doc_date FROM papers ORDER
  BY doc_date
  DESC;
 
  this just arranges them by day. e.g
 
 
  30/12/2005
  30/11/2005
  22/12/2005
  19/12/2005
  17/12/2005
  12/12/2005
  10/12/2005
  06/12/2007
  06/09/2002
  05/12/2005
  05/09/2005
 
 
 
  Now I have tried to use strtotime() but I find this needs a
  timezone (GMT)
  to work and I don't know if the server supports it. Also I
  find strototime()
  and mktime() very confusing and a things go wrong of you work
  in GMT because
  we also have Brittish Summer Time where the clocks get put
  back/forward at
  certain time of the year.
 
  Is there a simple function like sort() that could do it??
 

 Hi!

 Its a real shame your dates aren't stored in a DATE type field instead of
 VARCHAR, because you can just sort them in your query with order by DATE.
 If its possible, you would really benefit by converting them and storing
 them in the proper DATE type field.

 That being said, I suppose you could explode() them into an array then
 figure out how to sort them from there.

 JM

 --
 PHP General Mailing List (http://www.php.net/)
 To unsubscribe, visit: http://www.php.net/unsub.php



--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting dates with php

2005-12-21 Thread Chris Lott
On 12/21/05, Ross [EMAIL PROTECTED] wrote:
 Hi,

 Have a load of dates in the format DD/MM/YY. Thet are stored as a VARCHAR on
 a mysql DB.

Couldn't you use cast() to cast the values first? Something like (untested):

SELECT CAST(doc_date AS DATE) FROM papers ORDER BY doc_date DESC

c

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting users geographically...

2005-11-21 Thread David Grant
Hi Tony,

I would think the first step would be to find a web service or dataset
to convert a zip code to longitude/latitude.

The formula for calculating distances from long/lat is available here:

http://www.colorado.edu/geography/gcraft/warmup/aquifer/html/distance.html

Cheers,

David Grant

Tony Di Croce wrote:
 I'm helping a friend of mine build a matchmaking website, and we have a
 doozy of a problem to solve:
 
 What I need to do is two fold:
 
 #1 Collect whatever geographical information I need from each user to enable
 #2
 #2 Be able to run query's to find people NEAR (geographically) another
 person.
 
 Does anyone know of any commercial or free implementations of this? Is it
 primarily a database problem or is their some way (computationally) to
 compute the probable proximity of two zip codes?
 
 Hopefully someone responds to this with a Pear package that does exactly
 what I need! :) If that can't happen, then I'd appreciate any options you
 can think of.
 
 td
 
 --
 Free Linux Technical Articles
 http://www.linuxtecharticles.com
 

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] Sorting users geographically...

2005-11-21 Thread Jim Moseby
 
 I'm helping a friend of mine build a matchmaking website, and 
 we have a
 doozy of a problem to solve:
 
 What I need to do is two fold:
 
 #1 Collect whatever geographical information I need from each 
 user to enable
 #2
 #2 Be able to run query's to find people NEAR (geographically) another
 person.
 
 Does anyone know of any commercial or free implementations of 
 this? Is it
 primarily a database problem or is their some way (computationally) to
 compute the probable proximity of two zip codes?
 
 Hopefully someone responds to this with a Pear package that 
 does exactly
 what I need! :) If that can't happen, then I'd appreciate any 
 options you
 can think of.
 

http://sniptools.com/latitudeLongitude.php

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] Sorting users geographically...

2005-11-21 Thread Sandy Keathley
  Does anyone know of any commercial or free implementations of 
  this? Is it
  primarily a database problem or is their some way (computationally) to
  compute the probable proximity of two zip codes?


There is a class called zipLocator.  I think I found it at 
phpclasses.org.  It uses a large zipcode database, which can be 
downloaded for free (the address is in the class).

This will return all zipcodes within a specified distance from the 
target zipcode (10 mi, 50 mi, etc.).

If you can't find it, contact me offline.

Regards,

   SK


WebDesigns Internet Consulting
E-commerce Solutions
Application Development

Sandy Keathley
Zend Certified Engineer
[EMAIL PROTECTED]
972-569-8464

http://www.KeathleyWebs.com/


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting users geographically...

2005-11-21 Thread Marcus Bointon


On 21 Nov 2005, at 14:14, Tony Di Croce wrote:

Does anyone know of any commercial or free implementations of this?  
Is it

primarily a database problem or is their some way (computationally) to
compute the probable proximity of two zip codes?


All the suggested packages could be all you need, but also note that  
MySQL 5 has built-in GIS features which may make searches like these  
way more efficient should they use them:


http://dev.mysql.com/doc/refman/5.0/en/spatial-extensions-in-mysql.html
http://dev.mysql.com/doc/refman/5.0/en/functions-that-test-spatial- 
relationships-between-geometries.html


Marcus
--
Marcus Bointon
Synchromedia Limited: Putting you in the picture
[EMAIL PROTECTED] | http://www.synchromedia.co.uk

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting with french characters

2005-06-23 Thread Richard Lynch
On Thu, June 23, 2005 7:37 am, Mathieu Dumoulin said:
 STR_REPLACE on all possible accents, i got over a thousand records from
 the database to parse in a fast way and there are at the very least 60

Odds are REALLY GOOD you can get the database to ORDER BY using your
locale/language/charset of choice, and get it MUCH MUCH MUCH faster than
ksort.

You're should ask How on a mailing list for your database, though.

-- 
Like Music?
http://l-i-e.com/artists.htm

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] sorting object props

2005-06-18 Thread Richard Lynch
On Fri, June 17, 2005 2:48 pm, D_C said:
 is there a way to sort the properties of an object by their name, much
 like sort works on arrays?

 i am getting back an object from a database query and want to list the
 resulting items in alpha order by field name...

http://php.net/ksort

Last time I checked, PHP would still convert an object to an array if you
forced it to...

If not, there are introspective functions to examine your object and all
its properties, and surely you could build the array yourself and then
ksort it.

-- 
Like Music?
http://l-i-e.com/artists.htm

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] Sorting Objects in an array by object properties

2005-05-28 Thread Jared Williams

 Hello list,
 
 I have an array which holds some objects. Each object 
 represent elements from an email header in a given mailbox. 
 Each object has properties like from, sendtime, subject etc.
 
 I want to sort the order of the objects in the array by their 
 attribute sendtime in order to get a list of email header 
 sorted by their arrival time.
 
 Has anyone an idea how to solve this? I tried various of the 
 array sorting functions but without success.
 

http://php.net/usort 

function compare($h1, $h2)
{
return strcmp($h1-sendtime, $h2-sendtime);
}
usort($array, 'compare'); 

Jared

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting table columns dynamically on normalized MySQL tables

2005-04-22 Thread Richard Lynch
On Wed, April 20, 2005 5:53 am, Leif Gregory said:
 So joining on four tables isn't considered bad practice?

No, it's great practice.

The only thing to watch for is just how *BIG* will the number of tuples grow?

If you can multiply together the number of rows in all four tables and
come up with  1,000,000 you're fine.

If not, you have to start thinking about how you can get just the ones you
want for each query, and do it in such a way the MySQL never has to cope
with 1,000,000 rows at once.

Actually MySQL is quite happy to do 1,000,000 rows -- It's your hardware
that won't like it. :-)

So it really depends on what's *IN* the data, rather than the actual
number of tables.

Be sure you always get your WHERE clauses right.

One rule of thumb:

Work your way through all tables being joined from left to right:

FROM table1, table2, table3, table4, ...

For each tableX, make sure that you are relating it back to a previous
table, with an INDEXED key field in your WHERE clause with AND between
them:

WHERE table1.indexA = table2.indexB
  AND table2.indexC = table3.indexD
  AND table3.indexE = table4.indexE

It doesn't matter on table3 if you have it tied to table2 (as above) or
table 1 -- So long as the fields are indexed, and you can trace back from
every tableX to table1 *somehow*

But you wouldn't want just *this*

WHERE table1.indexA = table2.indexB
  AND table3.indexC = table4.indexD

You've got nothing to tie table3 and table4 back to table1, so every
single row in the 3/4 combination is going to be listed with every single
row with the 1/2 combination, in every possible permutation...

Try it with some very small (number of rows) tables just to see what happens!

-- 
Like Music?
http://l-i-e.com/artists.htm

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting table columns dynamically on normalized MySQL tables [LONG]

2005-04-20 Thread Leif Gregory
Hello Jay,

Tuesday, April 19, 2005, 1:28:25 PM, you wrote:
J Normalization has no effect on sort order where any DB is concerned.
J Sort order is determined in the sort clause in the query. So if you want
J to sort by location and you are using MySQL  your ORDER BY clause should
J be location(regardless of joins)

J SELECT foo
J FROM bar
J ORDER BY location

J returns

J course   instructor   location
J Science  Bill Elementary School
J Basket Weaving   Dave High School
J Math Dave Middle School
J Biology  Jessica  Middle School


Maybe I wasn't clear.

SELECT *
FROM Course
ORDER BY locationID ASC

Now the ORDER BY can be any one of five things based on the variable
passed by the hyperlink for the column they clicked on (location,
course, date, category, and instructor

Because locationID is an integer which directly relates to the
Instructors table id field (also an integer), there is no way in heck
that it can sort that any other way than numerically. There is no join
between the Course, Locations, and Instructors tables. All the Course
table knows is that there is an integer in the instructorID,
categoryID, and locationID field. Therefore it gets sorted
numerically, not alphabetically.

As I said, I was trying to keep the example simple. I actually have
the following tables in the DB.

Courses
Instructors
Locations
Categories
Students
Registrations
Supervisors

Courses contains information pertinent to a course.
 - id
 - name
 - courseDate
 - courseTime
 - ampm (morning or afternoon)
 - capacity (number of seats available)
 - locationID (corresponding id from the Locations table)
 - instructorID (corresponding id from the Instructors table)
 - seatsLeft (counter for the number of available seats)
 - description (what the course is about)
 - categoryID (corresponding id from the Categories table)

Instructors
 - id
 - firstName
 - lastName
 - email
 - phone
 - image
 - about

Locations
 - id
 - name
 - seatingCapacity (How many true seats there are in the room)
 - address
 - directions

Categories
 - id
 - name

Students
 - id
 - firstName
 - lastName
 - email
 - phone
 - password
 - username
 - divisionOrFacility
 - programArea
 - supervisorID

Supervisors
 - id
 - firstName
 - lastName
 - email
 - phone

Registrations
 - id
 - courseID
 - studentID
 - attended

So... For me to list the upcoming courses on the main page, I have the
following column in the table:

Course Name   - From Course Table
Open Seats- From Course Table
Category  - From Course Table (match id in Categories table)
Date  - From Course Table
Time  - From Course Table
Location  - From Course Table (match id in Locations table)
Instructor- From Course Table (match id in Instructors table)

Category, Location, and Instructor are integers. What I did to get the
names respective to the integer value is that beforehand I built an
array for those three tables then I match the id from the Course Table
for each of the three with their respective array, and then display
the name.

Since the SELECT statement is based on the Course table, and the
Course table contains only integers, it's sorting by the integer value
of the categoryID, instructorID, or locationID in the Course table.

The actual SELECT statement is as follows:

$sqlCourses=SELECT * FROM  . $tbl_courses .  WHERE courseDate  ' . 
date(Y-m-d) . ' ORDER BY  . $orderBy .  ASC;

the $orderBy variable is set via $_GET['orderBy'] which is sent by the
table headers as below:

$tblHeaders = 'tha href=' . $_SERVER['PHP_SELF'] . 
'?orderBy=nameCourse/a/ththOpen Seats/ththa href=' . 
$_SERVER['PHP_SELF'] . '?orderBy=categoryIdCategory/a/ththa href=' . 
$_SERVER['PHP_SELF'] . '?orderBy=courseDateDate/a/ththTime/ththa 
href=' . $_SERVER['PHP_SELF'] . '?orderBy=roomIdLocation/a/ththa 
href=' . $_SERVER['PHP_SELF'] . '?orderBy=instructorIdInstructor/a/th';

The sorting works just fine, but it's numerical ASC based off the
integer value (instructorID, categoryID, or locationID). It is *not*
alphabetical, which is what the customer wants.

If they sort by Location, the location column should be alphabetical
ASC, if by course name, then alphabetical ASC by the course name.

Is that a bit clearer now?

Sorry that this has degenerated into a MySQL question rather than PHP.
I was originally looking for how people handled it in PHP.

BTW, just for clarity sake on the arrays used to build the lookups to
display the list of courses, I'm doing an include with the following:



?php


//Get instructors --
$sqlInstructors=SELECT * FROM  . $tbl_instructors;
$resultInstructors=mysql_query($sqlInstructors) or die('Failed to get 
instructors. Please contact ' . $maintainer);

while ($rInstructors=mysql_fetch_assoc($resultInstructors))
{
  

Re: [PHP] Sorting table columns dynamically on normalized MySQL tables [LONG]

2005-04-20 Thread Chris Boget
 The actual SELECT statement is as follows:
 $sqlCourses=SELECT * FROM  . $tbl_courses .  WHERE courseDate  ' .
date(Y-m-d) . ' ORDER BY  . $orderBy .  ASC;
 the $orderBy variable is set via $_GET['orderBy'] which is sent by the
 table headers as below:

I'm curious why you aren't joining the other tables?  That will
solve all your woes...

thnx,
Chris

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] Sorting table columns dynamically on normalized MySQL tables [LONG]

2005-04-20 Thread Jay Blanchard
[snip]
SELECT *
FROM Course
ORDER BY locationID ASC

Now the ORDER BY can be any one of five things based on the variable
passed by the hyperlink for the column they clicked on (location,
course, date, category, and instructor
[/snip]

If you had a JOIN to the location table you could order by the actual
location. Here is an example...

SELECT c.courseName, l.locationName
FROM Course c, Location l
WHERE c.locationID = l.locationID
ORDER BY l.locationName

[snip]
Sorry that this has degenerated into a MySQL question rather than PHP.
I was originally looking for how people handled it in PHP.
[/snip]

Actually it didn't degenerate, it was a SQL question all along. Unless
you had a desire to build sortable arrays in PHP this type of sort
should always be done on the SQL side because it would be much more
efficient.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] Sorting table columns dynamically on normalized MySQL tables [LONG]

2005-04-20 Thread Jay Blanchard
[snip]
Sorry that this has degenerated into a MySQL question rather than PHP.
I was originally looking for how people handled it in PHP.
---
Actually it didn't degenerate, it was a SQL question all along. Unless
you had a desire to build sortable arrays in PHP this type of sort
should always be done on the SQL side because it would be much more
efficient.
[/snip]

I also should have said that it the joins that allow you to maintain
normalized tables, for without joins you would be stuck with doing the
magic in the programming language. Since most DB engines are optimized
for handling joins leave that efficiency on that side of the equation.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting table columns dynamically on normalized MySQL tables

2005-04-20 Thread Leif Gregory
Hello Kim,

Tuesday, April 19, 2005, 6:44:58 PM, you wrote:
K If you are still looking for tips and want to get
K complicated/fancy, I have seen columns used called sort_order more
K than a few times. This should not be too hard to maintain for
K things like a few buildings, etc., where the lookup table does not
K change much over time. You would then have another option for your
K oder by clause.

I understand what you mean, but I'm still in the same boat. There is
no join between the four tables (mainly because I didn't think you
were supposed to do joins on four tables. I've written a couple other
replies which I think more clearly state where my problem is so I
won't retype them here.

Thanks though.


-- 
Leif (TB lists moderator and fellow end user).

Using The Bat! 3.0.9.17 Return under Windows XP 5.1
Build 2600 Service Pack 2 on a Pentium 4 2GHz with 512MB

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting table columns dynamically on normalized MySQL tables

2005-04-20 Thread Leif Gregory
Hello Richard,

Tuesday, April 19, 2005, 9:12:14 PM, you wrote:
R Just build a JOIN query and do one query.

Doing a join on four tables is ok? (serious question, not being
facetious).

R No, it is *NOT* sorting on the ID number.

I can definitely say it is sorting on locationID, categoryID,
or instructorID. It's not alphabetical. When I view the listing after
a sort on say locationID, it's not alphabetical but ordered by which
class has the lowest numerical value in the locationID field and then
ASC from there.

R By definition, in SQL, if you don't specify a sort order (or in
R this case a second order) then the SQL engine can and will output
R the records in any order it feels like.

Really? I didn't know that. I thought it started at record 0 and then
output them in the order they appeared in the table data view (using
something like PHPMyAdmin.)


R In that case of MySQL and ISAM tables, that *HAPPENS* to be the ID
R order, because the under-lying SQL engine happens to find it
R convenient to have them in that order.

Ahhh. Ok, there we go.


R If you *DELETE* an ID number, then put another one in, but force it
R to be the same ID number you'll probably see the records come out
R in a different order. It's usually a really Bad Idea to do that
R (forcing an ID to be re-used) but for the purposes of
R learning/demonstration you can do it.

I'll give it a shot sometime to see. It'll be interesting to find out.


R At any rate, MySQL is *NOT* sorting by ID number. It's not sorting
R *AT* *ALL* except for what you told it to sort. It just spews out
R the records in any old order at all after location is done --
R Which happens to be ID order, but that's more like coincidence than
R plan [*].

Maybe I confused you with the ID nomenclature. I mean to say it's
sorting by locationID, categoryID, instructorID (whichever column I
clicked on), and since those are integer values they aren't sorted
alphabetically).


 That's not what they want obviously.
R Why not?
R What *DO* they want, then?

If they sort by location, they want the course records to show up in
alphabetical order based on location. Right now it does sort by
location, but it's not alphabetical because the Course.locationID,
Course.instructorID, and Course.categoryID are integers which relate
to three other respective tables. There is no join, and I didn't think
you were supposed to do a join on four tables.


R Do you want, perhaps, to have a DEFAULT sort order, which kicks in
R after their chosen ordering?

By default it sorts by Course date.


R Perhaps you could do (here's your magic bullet):

R ?php
R   $default_sort_order = course, instructor, location;
R   .
R   .
R   .
R   $query .= ORDER BY $_GET[order_by], $default_sort_order ;
?

I'm kinda doing that already as:

if (isset($_GET['orderBy']))
  $orderBy = $_GET['orderBy'];
else
  $orderBy = 'courseDate';


R Then, oddly enough, by location again, but that's kinda
R irrelevant. It won't *hurt* anything [**], mind you, it's just
R kinda silly, since you have already sorted by location in the very
R first place.

Got it.


R [**] Technically, it's a little inefficient to have that extra
R bogus location in there at the end, but you're probably not
R sorting enough rows for it to make any measurable difference in
R your results... And MySQL might even be smart enough to optimize it
R out anyway.

True enough. I'm guessing they'll be maybe 30 to 50 records at any one
time.

R You did the right thing. :-)

grin Tell me that again once I get the sorting working right! grin


R You just needed to go farther down the road you are on, instead of
R stopping partway.

Only stopped because I got stuck... :-)


Thanks.



-- 
Leif (TB lists moderator and fellow end user).

Using The Bat! 3.0.9.17 Return under Windows XP 5.1
Build 2600 Service Pack 2 on a Pentium 4 2GHz with 512MB

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting table columns dynamically on normalized MySQL tables

2005-04-20 Thread Leif Gregory
Hello Chris,

Tuesday, April 19, 2005, 1:23:53 PM, you wrote:
C Firstly, what DB are you using?

MySQL.

C SELECT
C   course.name,
C   location.name,
C   instructor.name
C FROM
C   course
C INNER JOIN location ON location.id = course.locationID
C INNER JOIN instructor ON instructor.id = course.instroctorID
C ORDER BY instructor.name

C (or location.name or course.name).

C It should be as simple as that...

So joining on four tables isn't considered bad practice? Technically
it's going to be five tables because the whole HTML table layout
changes to include enroll and disenroll buttons once they log in
and based on if they are enrolled or not in a particular course which
comes from the registrations table, which is simply their the id
from the Students table and the id from the Course table.

Thanks.


-- 
Leif (TB lists moderator and fellow end user).

Using The Bat! 3.0.9.17 Return under Windows XP 5.1
Build 2600 Service Pack 2 on a Pentium 4 2GHz with 512MB

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting table columns dynamically on normalized MySQL tables

2005-04-20 Thread Chris Boget
 R Just build a JOIN query and do one query.
 Doing a join on four tables is ok? (serious question, not being
 facetious).

Yes.  I've built a query before (for reporting purposes) that join
15 tables...  Just make sure the tables are indexed properly.

thnx,
Chris

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] Sorting table columns dynamically on normalized MySQL tables

2005-04-20 Thread Jay Blanchard
[snip]
Doing a join on four tables is ok? (serious question, not being
facetious).
[/snip]

Yes, it is OK. Make sure that you have the tables properly indexed and
you'll have no problems.

[snip]
R By definition, in SQL, if you don't specify a sort order (or in
R this case a second order) then the SQL engine can and will output
R the records in any order it feels like.

Really? I didn't know that. I thought it started at record 0 and then
output them in the order they appeared in the table data view (using
something like PHPMyAdmin.)
[/snip]

PHPMyAdmin uses an ORDER BY clause and it is initially on the primary
key index for any given table. Then PHPMyAdmin uses relevant column data
for the sort. SQL CAN and DOES spit out the records any way it wants
when no sort is specified. You dod not typically see it because of query
caching. (Ever notice that a second issue of the same query you just
made is much faster? Query caching.)

[snip]
R If you *DELETE* an ID number, then put another one in, but force it
R to be the same ID number you'll probably see the records come out
R in a different order. It's usually a really Bad Idea to do that
R (forcing an ID to be re-used) but for the purposes of
R learning/demonstration you can do it.

I'll give it a shot sometime to see. It'll be interesting to find out.
[/snip]

+1 on the bad idea for primary key re-use.

[snip]
If they sort by location, they want the course records to show up in
alphabetical order based on location. Right now it does sort by
location, but it's not alphabetical because the Course.locationID,
Course.instructorID, and Course.categoryID are integers which relate
to three other respective tables. There is no join, and I didn't think
you were supposed to do a join on four tables.
[/snip]

Furthering our discussion of the ORDER BY clause...you can put more than
one sort criteria there...

ORDER BY l.locationName, c.courseName

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting table columns dynamically on normalized MySQL tables

2005-04-19 Thread Chris Boget
 I can do that, but is there a better way? How do you all handle
 dynamic sorting of normalized DBs?

Firstly, what DB are you using?
Secondly, just select and sort on the columns.  An example query
would be:

SELECT
  course.name,
  location.name,
  instructor.name
FROM
  course
INNER JOIN location ON location.id = course.locationID
INNER JOIN instructor ON instructor.id = course.instroctorID
ORDER BY instructor.name

(or location.name or course.name).

It should be as simple as that...

thnx,
Chris

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



RE: [PHP] Sorting table columns dynamically on normalized MySQL tables

2005-04-19 Thread Jay Blanchard
[snip]
I can do that, but is there a better way? How do you all handle
dynamic sorting of normalized DBs?
[/snip]

Normalization has no effect on sort order where any DB is concerned.
Sort order is determined in the sort clause in the query. So if you want
to sort by location and you are using MySQL  your ORDER BY clause should
be location(regardless of joins)

SELECT foo
FROM bar
ORDER BY location

returns

course   instructor   location
Science  Bill Elementary School
Basket Weaving   Dave High School
Math Dave Middle School
Biology  Jessica  Middle School

The results with course as the sort qualifier

course   instructor   location
Basket Weaving   Dave High School
Biology  Jessica  Middle School
Math Dave Middle School
Science  Bill Elementary School

You have over-compicated a simple issue

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Sorting table columns dynamically on normalized MySQL tables

2005-04-19 Thread Kim Briggs
Greetings,

If you are still looking for tips and want to get complicated/fancy,
 I have seen columns used called sort_order more than  a few times. 
This should not be too hard to maintain for things like a few
buildings, etc., where the lookup table does not change much over
time.  You would then have another option for your oder by clause.

cheers,
KB

On 4/19/05, Jay Blanchard [EMAIL PROTECTED] wrote:
 [snip]
 I can do that, but is there a better way? How do you all handle
 dynamic sorting of normalized DBs?
 [/snip]
 
 Normalization has no effect on sort order where any DB is concerned.
 Sort order is determined in the sort clause in the query. So if you want
 to sort by location and you are using MySQL  your ORDER BY clause should
 be location(regardless of joins)
 
 SELECT foo
 FROM bar
 ORDER BY location
 
 returns
 
 course   instructor   location
 Science  Bill Elementary School
 Basket Weaving   Dave High School
 Math Dave Middle School
 Biology  Jessica  Middle School
 
 The results with course as the sort qualifier
 
 course   instructor   location
 Basket Weaving   Dave High School
 Biology  Jessica  Middle School
 Math Dave Middle School
 Science  Bill Elementary School
 
 You have over-compicated a simple issue
 
 --
 PHP General Mailing List (http://www.php.net/)
 To unsubscribe, visit: http://www.php.net/unsub.php
 


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



  1   2   3   >