Multi-sorting arrays ...

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Alan Searle

    Multi-sorting arrays ...

    I have been trying to get an array to sort on a particular column and
    have been having problems with my main key ...

    array_multisort ($dirlist["dirname"], SORT_DESC, SORT_STRING);

    This function takes an array ($dirlist) which has been loaded with a
    directory listing where each directory has its own index number
    ("dirid") and displays the listing in descending order by name
    ("dirname"). This works fine for the sorting of the names but the index
    number is reallocated (I assume because it is numeric) and I lose my
    link to the directory. arrgghh!

    How can I keep the rows 'together' and make sure that the index number
    and the name remain consistant?

    Any tips or snippets of syntax would be a great help.

    Regards,
    Alan Searle.
  • Pedro Graca

    #2
    Re: Multi-sorting arrays ...

    Alan Searle wrote:[color=blue]
    > I have been trying to get an array to sort on a particular column and
    > have been having problems with my main key ...
    >
    > array_multisort ($dirlist["dirname"], SORT_DESC, SORT_STRING);[/color]

    I've never used array_multisort () and I don't want to dive into the docs
    right now.

    Do you really need array_multisort () ?

    uasort($dirlist , 'cmp_function') ;

    and

    function cmp_function($l hs, $rhs) {
    if ($lhs['column'] < $rhs['column']) return 1;
    return ($lhs['column'] == $rhs['column']) ? 0 : -1;
    }


    --
    USENET would be a better place if everybody read: | to email me: use |
    http://www.catb.org/~esr/faqs/smart-questions.html | my name in "To:" |
    http://www.netmeister.org/news/learn2quote2.html | header, textonly |
    http://www.expita.com/nomime.html | no attachments. |

    Comment

    • Chung Leong

      #3
      Re: Multi-sorting arrays ...


      "Alan Searle" <aj_searle@xxxx yahoo.com> wrote in message
      news:cch22u$3aq $1@newsreader3. netcologne.de.. .[color=blue]
      > I have been trying to get an array to sort on a particular column and
      > have been having problems with my main key ...
      >
      > array_multisort ($dirlist["dirname"], SORT_DESC, SORT_STRING);
      >
      > This function takes an array ($dirlist) which has been loaded with a
      > directory listing where each directory has its own index number
      > ("dirid") and displays the listing in descending order by name
      > ("dirname"). This works fine for the sorting of the names but the index
      > number is reallocated (I assume because it is numeric) and I lose my
      > link to the directory. arrgghh!
      >
      > How can I keep the rows 'together' and make sure that the index number
      > and the name remain consistant?
      >
      > Any tips or snippets of syntax would be a great help.
      >
      > Regards,
      > Alan Searle.[/color]


      Comment

      • Chung Leong

        #4
        Re: Multi-sorting arrays ...

        "Alan Searle" <aj_searle@xxxx yahoo.com> wrote in message
        news:cch22u$3aq $1@newsreader3. netcologne.de.. .[color=blue]
        > I have been trying to get an array to sort on a particular column and
        > have been having problems with my main key ...
        >
        > array_multisort ($dirlist["dirname"], SORT_DESC, SORT_STRING);
        >
        > This function takes an array ($dirlist) which has been loaded with a
        > directory listing where each directory has its own index number
        > ("dirid") and displays the listing in descending order by name
        > ("dirname"). This works fine for the sorting of the names but the index
        > number is reallocated (I assume because it is numeric) and I lose my
        > link to the directory. arrgghh![/color]

        I have run into that problem before too. According to the manual
        array_multisort () is supposed to maintain key association but in actual use
        it changes the key. Use arsort() instead.


        Comment

        • Alan Searle

          #5
          Re: Multi-sorting arrays ...

          Chung Leong wrote:[color=blue]
          > "Alan Searle" <aj_searle@xxxx yahoo.com> wrote in message
          > news:cch22u$3aq $1@newsreader3. netcologne.de.. .
          >[color=green]
          >>I have been trying to get an array to sort on a particular column and
          >>have been having problems with my main key ...
          >>
          >>array_multiso rt($dirlist["dirname"], SORT_DESC, SORT_STRING);
          >>
          >>This function takes an array ($dirlist) which has been loaded with a
          >>directory listing where each directory has its own index number
          >>("dirid") and displays the listing in descending order by name
          >>("dirname") . This works fine for the sorting of the names but the index
          >>number is reallocated (I assume because it is numeric) and I lose my
          >>link to the directory. arrgghh![/color]
          >
          > I have run into that problem before too. According to the manual
          > array_multisort () is supposed to maintain key association but in actual use
          > it changes the key. Use arsort() instead.
          >[/color]
          I had a look at arsort() but it seems to cover single dimension arrays.
          Can I adapt it to work with a multi-dimension array?

          Thanks for your help.

          Rgds,
          Alan.

          Comment

          • Alan Searle

            #6
            Re: Multi-sorting arrays ...

            SNIP ...[color=blue]
            >
            > Do you really need array_multisort () ?[/color]

            Yes, array_multisort () seems to be a 'pain in the bottom' ... it messes
            up the key relationships. Arrgghh!
            [color=blue]
            > uasort($dirlist , 'cmp_function') ;
            >
            > and
            >
            > function cmp_function($l hs, $rhs) {
            > if ($lhs['column'] < $rhs['column']) return 1;
            > return ($lhs['column'] == $rhs['column']) ? 0 : -1;
            > }[/color]

            I would like to use your example but so far I can't get it to work. I am
            not sure how 'callback' functions operate: In your example here do I
            need to replace the word 'column' with the name of the column that I
            want to sort on? (that's what I did).

            And what are the parameters $lhs and $rhs (left hand side & right hand
            side?). I don't need to change these, do I?

            And how about descending order? I would just need to change '<' to '>',
            wouldn't I?

            Many thanks,
            Alan Searle

            Comment

            • Pedro Graca

              #7
              Re: Multi-sorting arrays ...

              [Please don't snip attributions]

              Alan Searle wrote:[color=blue]
              > Pedro Graca wrote:[color=green]
              >> uasort($dirlist , 'cmp_function') ;
              >>
              >> and
              >>
              >> function cmp_function($l hs, $rhs) {
              >> if ($lhs['column'] < $rhs['column']) return 1;
              >> return ($lhs['column'] == $rhs['column']) ? 0 : -1;
              >> }[/color]
              >
              > I would like to use your example but so far I can't get it to work.[/color]

              Post *your* code.
              [color=blue]
              > In your example here do I
              > need to replace the word 'column' with the name of the column that I
              > want to sort on? (that's what I did).[/color]

              Yes, you did right.
              [color=blue]
              > And what are the parameters $lhs and $rhs (left hand side & right hand
              > side?). I don't need to change these, do I?[/color]

              You don't need to change them. You may want to rename them to something
              more coherent with your naming structure.
              [color=blue]
              > And how about descending order?[/color]

              That particular 'cmp_function' already does a descending comparison.
              The ascending way returns -1 when $lhs < $rhs


              --
              USENET would be a better place if everybody read: | to email me: use |
              http://www.catb.org/~esr/faqs/smart-questions.html | my name in "To:" |
              http://www.netmeister.org/news/learn2quote2.html | header, textonly |
              http://www.expita.com/nomime.html | no attachments. |

              Comment

              • Alan Searle

                #8
                Re: Multi-sorting arrays ...

                Pedro Graca wrote:[color=blue]
                > [Please don't snip attributions]
                >
                > Alan Searle wrote:
                >[color=green]
                >>Pedro Graca wrote:
                >>[color=darkred]
                >>>uasort($dirl ist, 'cmp_function') ;
                >>>
                >>>and
                >>>
                >>>function cmp_function($l hs, $rhs) {
                >>> if ($lhs['column'] < $rhs['column']) return 1;
                >>> return ($lhs['column'] == $rhs['column']) ? 0 : -1;
                >>>}[/color]
                >>
                >>I would like to use your example but so far I can't get it to work.[/color]
                >
                >
                > Post *your* code.[/color]

                Code posted below ...
                [color=blue][color=green]
                >>In your example here do I
                >>need to replace the word 'column' with the name of the column that I
                >>want to sort on? (that's what I did).[/color]
                >
                > Yes, you did right.
                >[color=green]
                >>And what are the parameters $lhs and $rhs (left hand side & right hand
                >>side?). I don't need to change these, do I?[/color]
                >
                > You don't need to change them. You may want to rename them to something
                > more coherent with your naming structure.
                >[color=green]
                >>And how about descending order?[/color]
                >
                > That particular 'cmp_function' already does a descending comparison.
                > The ascending way returns -1 when $lhs < $rhs[/color]

                Hi Pedro,

                Many thanks for your help.

                At the moment the sort does not seem to have any effect on the sequence.
                Is the resorted data written back to the same array? Or should I be
                reading the data from a new array somewhere?

                Here is a copy of my code ...

                <html>
                <head>
                <title>Dir Sort</title>
                </head>
                <script language="php">

                print("start<br >");

                // Get a directory listing into dirlist ...
                $i=1;
                $dir = getcwd();

                if ($dh = opendir($dir)) {
                while (($file = readdir($dh)) !== false) {
                if (filetype($dir . "/" . $file)=="dir" AND $file != "." AND
                $file != "..") {
                // print("$file<br >");
                $dirlist["dirid"][$i]=$i;
                $dirlist["dirname"][$i]=$file;
                $direxp=explode ("_",$file); // replace underscore with blanks here
                $dirlist["dirstrip"][$i]=implode(" ",$direxp);
                $dirlist["dirfull"][$i]=$dir . "/" . $file;
                $i++;
                }
                }
                closedir($dh);
                }

                // run the uasort ...
                $success = uasort($dirlist , 'cmp_function') ;
                // print("success " . $success);

                // loop through the array and print the result ...
                $j=1;
                For ($j=1; $j<=$i - 1; $j++) {
                print($dirlist["dirid"][$j] . "/" . $dirlist["dirstrip"][$j] . "/"
                .. $dirlist["dirname"][$j] . "<br>");
                }

                // callback function (dirstrip is the column to sort on) ...
                function cmp_function($l hs, $rhs) {
                if ($lhs['dirstrip'] < $rhs['dirstrip']) return 1;
                return ($lhs['dirstrip'] == $rhs['dirstrip']) ? 0 : -1;
                }

                ?>

                </script>
                </body>
                </html>

                Comment

                • Pedro Graca

                  #9
                  Re: Multi-sorting arrays ...

                  Alan Searle wrote:[color=blue]
                  > // Get a directory listing into dirlist ...
                  > $i=1;[/color]

                  Why not 0?
                  [color=blue]
                  > $dir = getcwd();
                  >
                  > if ($dh = opendir($dir)) {
                  > while (($file = readdir($dh)) !== false) {
                  > if (filetype($dir . "/" . $file)=="dir" AND $file != "." AND
                  > $file != "..") {
                  > // print("$file<br >");
                  > $dirlist["dirid"][$i]=$i;
                  > $dirlist["dirname"][$i]=$file;
                  > $direxp=explode ("_",$file); // replace underscore with blanks here
                  > $dirlist["dirstrip"][$i]=implode(" ",$direxp);
                  > $dirlist["dirfull"][$i]=$dir . "/" . $file;[/color]

                  Aha! :)

                  IMHO you're building the array the wrong way around.

                  This way to do it, will not work with uasort() ... maybe
                  array_multisort (), I don't know.

                  If you do

                  $dirlist[$i]['dirid'] = $i;
                  $dirlist[$i]['dirname'] = $file;
                  // ...

                  instead, uasort() will work correctly (of course you'll have to change
                  your code to reflect the change in the array).

                  [color=blue]
                  > $i++;
                  > }
                  > }
                  > closedir($dh);
                  > }
                  >
                  > // run the uasort ...
                  > $success = uasort($dirlist , 'cmp_function') ;
                  > // print("success " . $success);
                  >
                  > // loop through the array and print the result ...
                  > $j=1;
                  > For ($j=1; $j<=$i - 1; $j++) {[/color]

                  I prefer a foreach() loop, but this also works.
                  [color=blue]
                  > print($dirlist["dirid"][$j] . "/" . $dirlist["dirstrip"][$j] . "/"
                  > . $dirlist["dirname"][$j] . "<br>");
                  > }[/color]
                  (snip)



                  Your $dirlist array has 4 elements (their keys are "dirid", "dirname",
                  ....). Each of these elements is itself another array with as many
                  elements as there are files in the directory.

                  If you change the way you build the array you get an array with as many
                  elements as there are files in the directory, in which every element is
                  itself another array with keys "dirid", ...


                  HTH

                  --
                  USENET would be a better place if everybody read: | to email me: use |
                  http://www.catb.org/~esr/faqs/smart-questions.html | my name in "To:" |
                  http://www.netmeister.org/news/learn2quote2.html | header, textonly |
                  http://www.expita.com/nomime.html | no attachments. |

                  Comment

                  • Alan Searle

                    #10
                    Re: Multi-sorting arrays ...

                    Pedro Graca wrote:[color=blue]
                    > Alan Searle wrote:
                    >[color=green]
                    >>// Get a directory listing into dirlist ...
                    >>$i=1;[/color]
                    >
                    >
                    > Why not 0?
                    >
                    >[color=green]
                    >>$dir = getcwd();
                    >>
                    >> if ($dh = opendir($dir)) {
                    >> while (($file = readdir($dh)) !== false) {
                    >> if (filetype($dir . "/" . $file)=="dir" AND $file != "." AND
                    >>$file != "..") {
                    >> // print("$file<br >");
                    >> $dirlist["dirid"][$i]=$i;
                    >> $dirlist["dirname"][$i]=$file;
                    >> $direxp=explode ("_",$file); // replace underscore with blanks here
                    >> $dirlist["dirstrip"][$i]=implode(" ",$direxp);
                    >> $dirlist["dirfull"][$i]=$dir . "/" . $file;[/color]
                    >
                    >
                    > Aha! :)
                    >
                    > IMHO you're building the array the wrong way around.
                    >
                    > This way to do it, will not work with uasort() ... maybe
                    > array_multisort (), I don't know.
                    >
                    > If you do
                    >
                    > $dirlist[$i]['dirid'] = $i;
                    > $dirlist[$i]['dirname'] = $file;
                    > // ...
                    >
                    > instead, uasort() will work correctly (of course you'll have to change
                    > your code to reflect the change in the array).
                    >
                    >
                    >[color=green]
                    >> $i++;
                    >> }
                    >> }
                    >> closedir($dh);
                    >> }
                    >>
                    >>// run the uasort ...
                    >>$success = uasort($dirlist , 'cmp_function') ;
                    >>// print("success " . $success);
                    >>
                    >>// loop through the array and print the result ...
                    >>$j=1;
                    >> For ($j=1; $j<=$i - 1; $j++) {[/color]
                    >
                    >
                    > I prefer a foreach() loop, but this also works.
                    >
                    >[color=green]
                    >> print($dirlist["dirid"][$j] . "/" . $dirlist["dirstrip"][$j] . "/"
                    >>. $dirlist["dirname"][$j] . "<br>");
                    >> }[/color]
                    >
                    > (snip)
                    >
                    >
                    >
                    > Your $dirlist array has 4 elements (their keys are "dirid", "dirname",
                    > ...). Each of these elements is itself another array with as many
                    > elements as there are files in the directory.
                    >
                    > If you change the way you build the array you get an array with as many
                    > elements as there are files in the directory, in which every element is
                    > itself another array with keys "dirid", ...
                    >
                    >
                    > HTH
                    >[/color]

                    Hi Pedro,

                    I had adapted my code (and reduced it a lot) but the sorting still
                    doesn't work. uasort seems to run successfully but the array still has
                    the old sort sequence.

                    I even tried adding 'x' to 'dirid' so that it was no longer a numeric.

                    Maybe you could take another quick look?

                    Many thanks,
                    Alan.

                    <html>
                    <head>
                    <title>Dir Sort</title>
                    </head>
                    <script language="php">

                    print("start<br >");

                    // Get a directory listing into dirlist ...
                    $i=0;
                    $dir = getcwd();

                    if ($dh = opendir($dir)) {
                    while (($file = readdir($dh)) !== false) {
                    if (filetype($dir . "/" . $file)=="dir" AND $file != "." AND
                    $file != "..") {
                    $dirlist[$i]['dirid']="x" . $i;
                    $dirlist[$i]['dirname']=$file;
                    $i++;
                    }
                    }
                    closedir($dh);
                    }

                    // run the uasort ...
                    $success = uasort($dirlist , 'cmp_function') ;

                    if ($success==true ) {
                    print('array multisort successful<br>' );
                    }

                    // loop through the array and print the result ...
                    For ($j=0; $j<$i; $j++) {
                    print($dirlist[$j]['dirid'] . "/" . $dirlist[$j]['dirname'] . "<br>");
                    }

                    // callback function (dirstrip is the column to sort on) ...
                    function cmp_function($l hs, $rhs) {
                    if ($lhs['dirname'] < $rhs['dirname']) return 1;
                    return ($lhs['dirname'] == $rhs['dirname']) ? 0 : -1;
                    }

                    ?>

                    </script>
                    </body>
                    </html>

                    Comment

                    • Pedro Graca

                      #11
                      Re: Multi-sorting arrays ...

                      Alan Searle wrote:[color=blue]
                      > I had adapted my code (and reduced it a lot) but the sorting still
                      > doesn't work. uasort seems to run successfully but the array still has
                      > the old sort sequence.
                      >
                      > I even tried adding 'x' to 'dirid' so that it was no longer a numeric.[/color]

                      No need for that.

                      (snip)[color=blue]
                      > // run the uasort ...
                      > $success = uasort($dirlist , 'cmp_function') ;[/color]

                      Aha! :-))
                      My error -- uasort *keeps* the associated keys, so that if you uasort()
                      the array

                      $a[0] = '4'; $a[1] = '1'; $a[2] = '2';

                      you get

                      $a[1] = '1'; $a[2] = '2'; $a[0] = '4';
                      // notice $a[0] in third place :)

                      instead of

                      $a[0] = '1'; $a[1] = '1'; $a[2] = '4';

                      just change the uasort() into usort() and it should be ok.

                      .... or print the array inside a foreach() loop :-)





                      Try this:

                      <?php
                      $a[2] = 'two';
                      $a[0] = 'zero';
                      $a[1] = 'one';

                      for ($i=0; $i<3; ++$i) echo $a[$i], ' ';
                      echo "\n<br/>\n";
                      foreach ($a as $v) echo $v, ' ';
                      ?>

                      --
                      USENET would be a better place if everybody read: | to email me: use |
                      http://www.catb.org/~esr/faqs/smart-questions.html | my name in "To:" |
                      http://www.netmeister.org/news/learn2quote2.html | header, textonly |
                      http://www.expita.com/nomime.html | no attachments. |

                      Comment

                      • Alan Searle

                        #12
                        Working OK ... Many thanks

                        Pedro Graca wrote:[color=blue]
                        > Alan Searle wrote:
                        >[color=green]
                        >>I had adapted my code (and reduced it a lot) but the sorting still
                        >>doesn't work. uasort seems to run successfully but the array still has
                        >>the old sort sequence.
                        >>
                        >>I even tried adding 'x' to 'dirid' so that it was no longer a numeric.[/color]
                        >
                        >
                        > No need for that.
                        >
                        > (snip)
                        >[color=green]
                        >>// run the uasort ...
                        >>$success = uasort($dirlist , 'cmp_function') ;[/color]
                        >
                        >
                        > Aha! :-))
                        > My error -- uasort *keeps* the associated keys, so that if you uasort()
                        > the array
                        >
                        > $a[0] = '4'; $a[1] = '1'; $a[2] = '2';
                        >
                        > you get
                        >
                        > $a[1] = '1'; $a[2] = '2'; $a[0] = '4';
                        > // notice $a[0] in third place :)
                        >
                        > instead of
                        >
                        > $a[0] = '1'; $a[1] = '1'; $a[2] = '4';
                        >
                        > just change the uasort() into usort() and it should be ok.
                        >
                        > ... or print the array inside a foreach() loop :-)
                        >
                        >
                        >
                        >
                        >
                        > Try this:
                        >
                        > <?php
                        > $a[2] = 'two';
                        > $a[0] = 'zero';
                        > $a[1] = 'one';
                        >
                        > for ($i=0; $i<3; ++$i) echo $a[$i], ' ';
                        > echo "\n<br/>\n";
                        > foreach ($a as $v) echo $v, ' ';
                        > ?>[/color]

                        Hi Pedro,

                        Yes, it worked! Many thanks.

                        And thanks for the little 'foreach' example. This helps me to 'get my
                        head around' some aspects of array handling.

                        Cheers,
                        Alan.

                        Comment

                        Working...