Using numbers to access elements in arrays

Martin Baxter martin at harbourtown.co.uk
Fri Aug 8 03:03:01 EDT 2003


>Trevor DeVore wrote
>On 8/7/03 Martin Baxter wrote
>>
>>If you have to modify the data and also need to read the data out in
>>numeric order as if the keys were integers in sequence, you can:
>>
>>put the keys of theArray into akeys
>>sort numeric lines of akeys
>>repeat for each line i in akeys
>>  put theArray[i] into something
>>end repeat

>This works great for one dimensional arrays.  I'm wondering if there is a
>clean way of doing something similar for multi-dimensional arrays.  Lets
>say my array looks like this:
>
>myArray[1,"RecID"]
>myArray[1,"Name"]
>myArray[6,"RecID"]
>myArray[6,"Name"]
>myArray[3,"RecID"]
>myArray[3,"Name"]
>myArray[2,"RecID"]
>myArray[2,"Name"]
>
>I can use your technique above to sort the keys with something like:
>
>set itemDelimiter to ","
>put keys of myArray into tKeys
>sort lines of tKeys ascending numeric by item 1 of each
>
>But when I do my loop:
>
>repeat for each line tRec in tKeys
>    blah, blah, blah
>end repeat
>
>I am looping over each line rather than each key.  With each iteration I
>want to go from key to key rather than line to line.  Is there a way to
>make the repeat structure loop over each key rather than each line?  I do
>a lot of array manipulation in PHP and this is one of the few things I
>find I miss in Rev.
>

I heartily agree that more array flexibility would be welcome in
Revolution, and PHP does "spoil us rotten" in that respect.

In the case you cite, just sorting the keys by item 1 might not necessarily
end up with the result you assume above.
To get that reliably I think you would need to have 2 levels of sorting,
the first numeric and the second alphanumeric..
Alternatively you might address the problem inside the loop.

Assuming the array keys are known to be "dimensionally consistent"
throughout, my first instinct would be to try something like the following
(untested) :

## do your keysort by item 1
put empty into bunchHolder
put 1 into bunchCounter
repeat for each line tRec in tKeys
  if bunchCounter = 1 then
      put myArray[tRec] into bunchHolder
      put 2 into bunchCounter
  else if bunchCounter = 2 then
      put myArray[tRec] into line 2 of bunchHolder
      sort lines of bunchHolder
      # do what you need to do
      put 1 into bunchCounter
  end if
end repeat

martin





More information about the use-livecode mailing list