Sorting an array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • beary
    New Member
    • Nov 2006
    • 170

    Sorting an array

    If I have

    $array1=array(3 ,7,12,56,89);
    $array2=array(1 2,89,3,7,56);

    Is it possible to sort $array1 so that it's in the same order as $array2? Ie. so $array1=array(1 2,89,3,7,56);
  • Markus
    Recognized Expert Expert
    • Jun 2007
    • 6092

    #2
    Originally posted by beary
    If I have

    $array1=array(3 ,7,12,56,89);
    $array2=array(1 2,89,3,7,56);

    Is it possible to sort $array1 so that it's in the same order as $array2? Ie. so $array1=array(1 2,89,3,7,56);
    Could you explain why? It seems to me you want 2 arrays with exactly the same content.. which seems slightly wasteful.

    Comment

    • beary
      New Member
      • Nov 2006
      • 170

      #3
      Originally posted by Markus
      Could you explain why? It seems to me you want 2 arrays with exactly the same content.. which seems slightly wasteful.
      Sure Markus,

      array1 is an array of files
      I have then had to do some mapping to get the correct order to display each of the files.
      After that mapping, it turns out the correct order is the order of array2.
      I can't just "refill" array1 with the actual files, so I need to sort array1 in the order of array2 before I display them. (There is no "natural" order to array2's files; it's not like they're alphabetically ordered or anything - that would make it easy)

      Does this make sense?

      I'm sure php can somehow do it. I have spent a number of hours on this, but have not had any success yet, and I decided it was time to get some more knowledgable people to help me :)

      Comment

      • ghostdog74
        Recognized Expert Contributor
        • Apr 2006
        • 511

        #4
        Originally posted by beary
        If I have

        $array1=array(3 ,7,12,56,89);
        $array2=array(1 2,89,3,7,56);

        Is it possible to sort $array1 so that it's in the same order as $array2? Ie. so $array1=array(1 2,89,3,7,56);
        you can just assign array1 the values of array2
        Code:
        $array1=array(3,7,12,56,89);
        print_r($array1);
        $array2=array(12,89,3,7,56);
        print_r($array2);
        $array1=$array2;
        print_r($array1);

        Comment

        • beary
          New Member
          • Nov 2006
          • 170

          #5
          Originally posted by ghostdog74
          you can just assign array1 the values of array2
          Thanks ghostdog,

          I wish it were that easy... I already tried that. It breaks the whole thing. I think it's because the numbers are actually files. So I have this array of files that I need to sort, and so just making array1 (the files) = array2( the numbers representing the files) replaces files with numbers and it breaks. I really do need to be able to sort the original array1.

          Comment

          Working...