For Programmers: Free Programming Magazines  


Home > Archive > PHP DB > March 2006 > Re-arranging elements in an associative array









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Re-arranging elements in an associative array
Fred Riley

2006-03-24, 7:57 am

Hi

This is my first question to these NGs, so please be gentle with me in any replies :). I've crossposted it as I'm not sure which is the more appropriate group.

I'm a relative newbie to PHP, and my Q in short is: is there an easy way to manually change the arrangement of elements in an associative array?

I'll use an example from the PHP manual:

$a = array( 'color' => 'red',
'taste' => 'sweet',
'shape' => 'round',
'name' => 'apple',
);

If you then iterate through this with foreach() to print it out then the keys and values will be printed in the order above. What I'd like to do is, say, move $a['name'] up to 2nd place, so that it would print in the order:

'color'
'name'
'shape'
'name'

I don't want to sort the array, just rearrange it a bit. I've looked in the array function list in TFM but can't see anything appropriate, and I couldn't see anything on PX or phpbuilder.

The reason I want to do this is to arrange the values in a row extracted from mySQL. If you click on any of the titles in my test database browse page at http://www.nottingham.ac.uk/~ntzfr/.../rlo_titles.php you should get a 'full record' page.
The fields from "RLO No." down to "Record last updated" are extracted from a single table 'RLO' with a simple SELECT query and their names and values are stuck into the associative array $record. The fields below (Author, Developer, etc) are extracted fro
m junction tables by separate join queries, and also assigned to $record. The table is then printed with a simple foreach loop. What I'd like to do is shift, say, "Author" after "RLO title", "Developer" after "Stage", and so on.

I could do this the clunky way, by manually assigning each key and value from the queries into an array with the elements in the required order, and I'll do that if there's no easy way of rearranging elements. I suppose I could use some complex combinatio
n of shift(), pop(), merge() and whatnot, but that would probably take up more time than the clunky way. TIA for any suggestions/tips.

Cheers

Fred
Learning Technologist
School of Nursing, University of Nottingham
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com