473,769 Members | 2,331 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

print order of assoctive array



Ive got a series of 2 dimensional associative arrays
while(list($key , $val) = each ($results))
{
{foreach($val as $i=>$v)
print "$i = $v";
}
}
but i want to define the order that the various $i's are printed in
(not numerical/alphabetically)

arrays named
"key1_sorted_or der" = keys in the order to be printed
"key2_sorted_or der"

ive been experimeting with

while(list($key , $val) = each ($results))
{
{foreach($val as $i=>$v)
$ks=$i.'_sorted _order';
($cntr=0;cntr<c ount($ks);$cntr ++ )
{ print [$ks[$cntr]] =$results[$val[$ks[$cntr]]]
}
}
}

anyone able to help me out ?

Dec 2 '05 #1
7 2159
pauld wrote:


Ive got a series of 2 dimensional associative arrays
while(list($key , $val) = each ($results))
{
{foreach($val as $i=>$v)
print "$i = $v";
}
}
but i want to define the order that the various $i's are printed in
(not numerical/alphabetically)

arrays named
"key1_sorted_or der" = keys in the order to be printed
"key2_sorted_or der"

ive been experimeting with

while(list($key , $val) = each ($results))
{
{foreach($val as $i=>$v)
$ks=$i.'_sorted _order';
($cntr=0;cntr<c ount($ks);$cntr ++ )
{ print [$ks[$cntr]] =$results[$val[$ks[$cntr]]]
}
}
}

anyone able to help me out ?


Hi,

I just wrote a similar routine yesterday. :-)
Try this:

Move every element in your array to a new array, using an assoc-index of
your choice, and thus defining the ordering.
ksort ($newarray)

Works like a charm.

If the default ksort is not to your liking, use uksort.

Good luck

Regards,
Erwin Moller
Dec 2 '05 #2
Erwin Moller wrote:
Move every element in your array to a new array


Why? Just apply uksort to $val (the 2nd level array).

--
E. Dronkert
Dec 2 '05 #3
I read that but couldnt see how to apply it

the keys in the assoc array and the order id like then to appear are
('21', 'NC2', 'NC4', '28', '35', '40', '50', '60', '80', '100')

( if you are interested its the % oxygen you can administer )

Dec 2 '05 #4
pauld wrote:
the keys in the assoc array and the order id like then to appear are
('21', 'NC2', 'NC4', '28', '35', '40', '50', '60', '80', '100')


$oxchr = array('21', 'NC2', 'NC4', '28', '35', '40', '50', '60', '80',
'100');
$oxord = array_flip($oxc hr);

function oxkeysort($k1, $k2) {
global $oxord;
return $oxord[$k1] - $oxord[$k2];
}

uksort($val, 'oxkeysort');

--
E. Dronkert
Dec 2 '05 #5
Ewoud Dronkert wrote:
Erwin Moller wrote:
Move every element in your array to a new array


Why? Just apply uksort to $val (the 2nd level array).


Hi Ewoud,

Yes, you are right.

The situation I was describing was an array with a complex structure per
element that it contained (more arrays actually, but complex sounds so
great).

The underlying arraystructure differed from element to element.

For some stupid reason I thought the function called by uksort could only
operate on single simple values, which turned out to be nonsense.
(I guess I guessed wrong, based on my experiences with Java, where that
logic is just implemented a little differently for sorting.)

I reread the uksort-function, and the function used just receives the
elements, which can be used to look deeper into their arrays.

Anyway, I got it now.
I will be using uksort a lot more now, so thanks.

You just made my life a little easier (and my code a little faster).
:-)

Regards,
Erwin Moller
Dec 2 '05 #6
thanks -great help. Got the first one working not sure i quite
understand it though (!)
the added problem is that I have a series of these and would ideally
like to to generate the array name dynamically.The array_push is an
attempt to make the code generic

eg for 2 of them I can do

if ($key=="oxy") {
foreach($oxysor ted as $v)
{array_push($so rted,$v);}
$oxord = array_flip($sor ted);
uksort($val, 'keysort');
print '<table summary="" border=2>';
foreach($val as $i=>$v){print '<tr><td>'.$i." =>".$v.'</td></tr>';
}
}
else if ($key=="physio" ) {
foreach($physio sorted as $v){array_push( $sorted,$v);}
$oxord = array_flip($sor ted);
uksort($val, 'keysort');
print '<table summary="" border=2>';
foreach($val as $i=>$v){print '<tr><td>'.$i." =>".$v.'</td></tr>';
}
}

Ive tried genertign the array name dynamically but it doesnt revognise
it as an array
eg
$varsorted=$key .'sorted';
and replacing the ($oxysorted as $v) and ($physiosorted as $v) with
($varsorted as $v) but it doenst like it .

I *think* its the php equivalent of perls $$variable that Im after

Dec 13 '05 #7
pauld wrote:
the added problem is that I have a series of these and would ideally
like to to generate the array name dynamically.


First an explanation of what I wrote earlier:

$oxchr = array(
'21', 'NC2', 'NC4', '28', '35', '40', '50', '60', '80', '100');
$oxord = array_flip($oxc hr);

function oxkeysort($k1, $k2) {
global $oxord;
return $oxord[$k1] - $oxord[$k2];
}

uksort($val, 'oxkeysort');

The $oxchr array contains all the keys of the array that you want sorted,
in the order that you want them sorted. Not shown but implied by omitting
them are the numerical keys of the $oxchr array, from 0 for '21' to 9 for
'100'. 'Flipping' an array means switching each key-value pair. So $oxord
contains array('21' => 0, 'NC2' => 1, ..., '100' => 9). I loaned the
variable names from the chr() and ord() functions because $oxchr[1] gives
'NC2' while $oxord['NC2'] gives 1, much the same as chr(65) is 'A' and
ord('A') is 65. It means you can determine the order of the oxygen label
keys by accessing the $oxord array. The oxkeysort() function does just
that by returning the difference between two $oxord values. Zero means
that the same key was used, negative means that the first was smaller than
the second (ie. already sorted in ascending order) and positive the
reverse: 1 was bigger than 2, must be swapped for ascending order.
Finally, the uksort() function puts it to good use by sorting the $val
array using the supplied function for comparing the keys of $val, those
keys being the same oxygen labels defined as values in $oxchr.

Now, if you want to have more user defined sorting orders, my first
instinct would be to expand the chr and ord arrays to 2 dimensions:

$mychr = array(
'oxy' => array(
'21', 'NC2', 'NC4', '28', '35', '40', '50', '60', '80', '100'),
'physio' => array(
'John', 'Joe', 'Anne', 'Marie'));
$myord = array();
foreach ($mychr as $k => $v)
$myord[$k] = array_flip($v);

So $mychr['oxy'] is the same as $oxchr previously, likewise $myord['oxy']
and $oxord. In addition, you now have $myord['physio'].

My second idea would be to maintain the idea of my first code snippet: to
use a global variable in the user defined sort function for accessing the
sort order. But that order can now be different each time. So use a
"pointer" to the currently used one:

$curord = 'oxy';
function mykeysort($k1, $k2) {
global $myord, $curord;
return $myord[$curord][$k1] - $myord[$curord][$k2];
}

Or perhaps one level up for slightly simpler code inside the function,
although speed of execution could go either way depending on size of the
arrays and calling frequency of the different functions:

$curord = $myord['oxy'];
function mykeysort($k1, $k2) {
global $curord;
return $curord[$k1] - $curord[$k2];
}

Of course, the global $curord need not be set right away. Each time before
you call uksort(), first set the appropriate sort order:

$curord = 'oxy'; //or $curord = $myord['oxy'];
uksort($val, 'mykeysort'); //$val contains oxygen label keys

$curord = 'physio'; //or $curord = $myord['physio'];
uksort($val, 'mykeysort'); //$val contains physio label keys

As you can see, the function name inside uksort() doesn't change. You must
update $curord each time though, which I think you can do "dynamicall y".

--
E. Dronkert
Dec 13 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
4360
by: Ricki Susic | last post by:
Hi, Can anyone help me to get my query printed when I parse ID. Here is the code: FILE: udskriv.php <?php
1
2864
by: Sue Adams | last post by:
I have a form on an asp page and am trying to write the code to place the values of all checkboxes that have been selected, into an array. The checkbox values will be used in a dynamic sql statement to retrieve information from an access database, to be displayed ont he page. Since I''ve never worked with arrays before I''ve been running tests and displaying values on the next page to help me figure out my code. my array code reads like this:...
8
7599
by: vijay | last post by:
Hello, As the subject suggests, I need to print the string in the reverse order. I made the following program: # include<stdio.h> struct llnode { char *info;
1
2323
by: Steff | last post by:
I am wandering if my code is making sense... I use a lot the print function. Is it weird in this case where I have to display an array ? I thought it would be better to have the entire array in php but now I am not sure if that makes sense. Can you tell me please ? <html> <head>
3
10581
by: Eric Lilja | last post by:
Assignment: Create a 3x4 2-dimensional array of integers. Populate each element using some non-random scheme so that no two elemens contain the same value. Then create two functions for printing the 2D array. One should only work for set column size, accepting only the number of rows as an additional argument, one should accept both the number of rows and columns as arguments. So, I came up with: #include <stdio.h>
3
2109
by: James J. Besemer | last post by:
I would like to champion a proposed enhancement to Python. I describe the basic idea below, in order to gage community interest. Right now, it's only an idea, and I'm sure there's room for improvement. And of course it's possible there's some serious "gotcha" I've overlooked. Thus I welcome any and all comments. If there's some agreement that this proposal is worth further consideration then I'll re-submit a formal document in...
22
8047
by: joshc | last post by:
In an interview for an embedded software position recently I was asked to write code, in C, for printing the contents of a linked list backwards. After a few minutes I came up with the recursive solution. Being that recursion is frowned upon in embedded software, the answer was not what the interviewer expected, but alas it was correct. I asked some friends how they would have answered and another answer is to reverse the list and then...
1
1729
by: Alan G | last post by:
I'm grateful for any help here! My program is generally quite a simple problem; must read in a list containing names and numbers and print it out like a phonebook in alphabetical order, in order of surname, comma, forename, and a number in a 2nd column. An example of the input is: Fred Flintstone 555437 John Wayne 645373 Michael Schumacher 0343653 etc. And the output should be:
6
2149
by: mattmao | last post by:
Okay, this is just my exercise in order to prepare for the coming assignment regarding the damned Linked List issue... The task is simple and I am about to finish it. However, I couldn't go around one last bit: how to print out the elements? Here is so far what I've got: #include <stdio.h> #include <stdlib.h> struct intRecord
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10222
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10050
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9999
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7413
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6675
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
3570
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.