SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Evangelist
    Join Date
    Nov 2009
    Posts
    471
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Processing a sorted multi-dimensional array

    I have an array of structure $arrname['name'][0,1,2,3,4,...], $arrname['city'][0,1,2,3,4,...], $arrname['state'][0,1,2,3,4,...] and if I do an asort($arrname['name']) it performs the sort just fine by name and maintains the indexing so I can access the other elements by index.

    But how do I now process the array since the index is out of order. Normally I would use a FOR statement processing from 0 to count but since the name array is no longer in index order, it wipes out the sort.

    So I assume I need to process the name array sequentially and reference the other two elements by index which I would need to get from the name element. Is there a way in PHP to process the array sequentially by ordered name element and reference the index of the sorted name element?

    Thanks

  2. #2
    SitePoint Evangelist
    Join Date
    Nov 2009
    Posts
    471
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I think I found the answer. If I use array_keys to create an array of the $arrname['name'][] elements and then process the array_keys result in a FOR statement, it gives me the corresponding array indexes for each name element in sorted order. Seems to work fine.

  3. #3
    From Italy with love silver trophybronze trophy
    guido2004's Avatar
    Join Date
    Sep 2004
    Posts
    9,496
    Mentioned
    163 Post(s)
    Tagged
    4 Thread(s)
    If you use
    PHP Code:
    foreach ($arrname['name'] as $key => $value
    that should give you the key for each 'name' element too.

  4. #4
    SitePoint Evangelist
    Join Date
    Nov 2009
    Posts
    471
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Excellent, thanks for the input. I do appreciate it. I was starting to look into foreach when I ran across the other solution so this helps make it more clear.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •