Jump to content

sorting a multidimensional array


lordy16

Recommended Posts

what I'm looking to do is this:

 

say i have a multidimensional array like so:

 

    [0] => {
      ['name'] => "Baby, Please Don't Go"
      ['artist'] => {
                    [0]=> "AC/DC"
                    }
    }
    [1] => {
      ['name'] => "Tequila"
      ['artist'] => {
                    [0] => "A.L.T. and The Lost Civilization"
                    }
    }
    [2] => {
      ['name'] => "Show You Love Me"
      ['artist'] => {
                    [0] => "A.K. Soul"
                    [1] => "Jocelyn Brown"
                    }
    }
    [3] => {
      ['name'] => "Dog Eat Dog"
      ['artist'] => {
                    [0] => "AC/DC"
                    }
    }

 

 

How can I get it to sort by a specific key, for example the first artist key, alphabetically so it ends up like this:

 

    [0] => {
      ['name'] => "Baby, Please Don't Go"
      ['artist'] => {
                    [0]=> "AC/DC"
                    }
    }
    [1] => {
      ['name'] => "Dog Eat Dog"
      ['artist'] => {
                    [0] => "AC/DC"
                    }
    }
    [2] => {
      ['name'] => "Show You Love Me"
      ['artist'] => {
                    [0] => "A.K. Soul"
                    [1] => "Jocelyn Brown"
                    }
    }
    [3] => {
      ['name'] => "Tequila"
      ['artist'] => {
                    [0] => "A.L.T. and The Lost Civilization"
                    }
    }

ie. re-arrange the entire array depending on one branch of the array.

 

I hope that is clear enough lol i hope it's possible

Link to comment
Share on other sites

I am getting the information from the database btu unfortunately with the way ive retreived the data and the set up of my database i couldn't think of any way to use SORT BY to sort my information, hence why i thought i would be able to do it by putting it into an array before i printed the information.

Link to comment
Share on other sites

Ok, this is not difficult. There are functions in PHP just for sorting multi-dimensional arrays. But, Daukan is also correct that this would be best done when querying the data. Why don't you post the query you are using and we'll see if it can be sorted that way. If not, you can use the function array_multisort(): http://us3.php.net/manual/en/function.array-multisort.php

Link to comment
Share on other sites

the issue is that I'm using multiple queries to get the data, so i can't sort them in the query.

 

i looked at that function, but from what i understood of it, that only sorts within the one branch of the array, it doesn't rearrange the entire array based on one key within a branch, if that makes sense. maybe i'm misunderstanding it?

Link to comment
Share on other sites

the issue is that I'm using multiple queries to get the data, so i can't sort them in the query.

 

i looked at that function, but from what i understood of it, that only sorts within the one branch of the array, it doesn't rearrange the entire array based on one key within a branch, if that makes sense. maybe i'm misunderstanding it?

 

Ok, then show us the queries you are using. I have a feeling it can be done. however, you must not have read through array_multisort() because it can do what you want. There is also usort().

 

I will be happy to help. Not being rude, but the fact that you don't know how to sort a multidimensional array and are here asking for help you should be a little open to someone suggesting that there is a better way. Please post the code you use to runthe queries and build the array. I will try to either 1) reduce to one, sorted query or 2) will provide code to sort your multi-dimensional array.

Link to comment
Share on other sites

im sorry im more than open to people suggesting there is a better way :s

if that function can do what i want could you possibly post an example code showing how to do what i put in my example? because i honestly don't understand it.

 

as the code stands at the moment its not building an array, its just printing the unsorted data. but anyway here it is:

if(isset($_POST['artist'])) {
$artist = mysql_escape_string(urldecode($_POST['artist']));
}

if(isset($_POST['aust'])) {
$aust = 1;
}

if(isset($artist)) {
  $query1 = "SELECT art_id FROM book_artist WHERE art_name='" . $artist . "'";
  if(isset($aust) && $aust==1) {
    $query1 .= " AND art_aust='1'";
  }
  $query1 = $db->query($query1);
  if($query1) {
    if(mysql_num_rows($query1) > 0) {
      $result1 = $db->fetch($query1);
      $artid = $result1['art_id'];
      $query2 = "SELECT song_id FROM art_assoc WHERE art_id=" . $artid;
      $query2 = $db->query($query2);
      if($query2) {
        if(mysql_num_rows($query2) > 0) {
          while($result2 = $db->fetch($query2)) {
            $songid[] = $result2['song_id'];
          }
          for($a=0;$a<count($songid);$a++) {
            $query3 = "SELECT * FROM book_songs WHERE (song_id=" . $songid[$a] . ")";
            if(isset($title)) {
              $query3 .= " AND (song_title='" . $title . "')";
            }
            if(isset($date1)) {
              $query3 .= " AND ((song_ed >= '" . $date1 . "') AND (song_ed <= '" . $date2 . "'))";
            }
            if(isset($songpeak1)) {
              $query3 .= " AND ((song_peak >= '" . $songpeak1 . "') AND (song_peak <= '" . $songpeak2 . "'))";
            }
            $query3 = $db->query($query3);
            if($query3) {
              if(mysql_num_rows($query3) > 0) {
                $result3 = $db->fetch($query3);
                $query4 = "SELECT * FROM art_assoc WHERE song_id=" . $result3['song_id'];
                $query4 = $db->query($query4);
                if($query4) {
                  while($result4 = $db->fetch($query4)) {
                    $query5 = "SELECT * FROM book_artist WHERE art_id=" . $result4['art_id'];
                    $query5 = $db->query($query5);
                    if($query5) {
                      $result5 = $db->fetch($query5);
                      $artnames[] = $result5['art_name'];
                      if($result5['art_aust'] == "1") {
                        $austsong = "true";
                      } else {
                        if(isset($austsong)) {
                          if($austsong=="true") {
                            $austsong="true";
                          }
                        } else {
                          $austsong="false";
                        }
                      }
                    } else {
                      print "Error retrieving artist data!";
                      exit();
                    }
                  }
                  $query6 = "SELECT * FROM label_assoc WHERE song_id=" . $result3['song_id'];
                  $query6 = $db->query($query6);
                  if($query6) {
                    while($result6 = $db->fetch($query6)) {
                      $query7 = "SELECT label_name FROM book_labels WHERE label_id=" . $result6['label_id'];
                      $query7 = $db->query($query7);
                      if($query7) {
                        $result7 = $db->fetch($query7);
                        $labnames[] = $result7['label_name'];
                      }
                    }
                    print "<div class=\"songres\"";
                    if($austsong=="true") {
                      print " style=\"background-color:#7eadfc;\"";
                    }
                    print ">";
                    print "<span class=\"songtitle\">";
                    print $result3['song_title'];
                    print "</span><br />";
                    print "<span class=\"songartist\">";
                    for($n=0;$n<count($artnames);$n++) {
                      print $artnames[$n];
                      if($n<(count($artnames)-1)) {
                        print ", ";
                      }
                    }
                    print "</span><br />";
                    print "<span class=\"songcatlab\"><span class=\"bold\">";
                    for($m=0;$m<count($labnames);$m++) {
                      print $labnames[$m];
                      if($m<(count($labnames)-1)) {
                        print ", ";
                      }
                    }
                    print "</span>  <span style=\"font-style:italic;\">";
                    print $result3['cat_num'];
                    print "</span></span><br /><br />";
                    print "<span class=\"bold\">Entry Date: </span>";
                    $datearr = explode("-",$result3['song_ed']);
                    print $datearr[2] . "/" . $datearr[1] . "/" . $datearr[0];
                    print "   <span class=\"bold\">Entry Point: </span>#";
                    print $result3['song_ep'];
                    print "   <span class=\"bold\">Chart Peak: </span>#";
                    print $result3['song_peak'];
                    print "   <span class=\"bold\">Total Weeks: </span> ";
                    print $result3['song_tw'];
                    print "<br /><span class=\"bold\">Notes: </span> ";
                    print $result3['song_notes'];
                    print "</div>";
                    print "<br />";
                    unset($labnames,$artnames);
                  } else {
                    print "Error retrieving data!";
                    print "1";
                  }
                } else {
                  print "Error retrieving data!";
                  print "2";
                }
              }
            } else {
              print "Error retrieving data!";
              print "3";
            }
          }
        }
      } else {
        print "Error retrieving data!";
        print "4";
      }
    }
  } else {
    print "Error retrieving data!";
    print "5";
  }
} 

 

I know that that is sorted by artist since I'm pulling out the artist data first and then looping through the songs, but what i am having issues with is if the user wants to sort by something else, ie the song peak field in the book_songs table. anyway i hope you understand.

Link to comment
Share on other sites

I know that that is sorted by artist since I'm pulling out the artist data first and then looping through the songs

 

That's the exact problem I was suspecting. You are looping through records and doing sub-queries instead of using a JOIN in your queries.

 

For example in this code:

                $query4 = "SELECT * FROM art_assoc WHERE song_id=" . $result3['song_id'];
                $query4 = $db->query($query4);
                if($query4) {
                  while($result4 = $db->fetch($query4)) {
                    $query5 = "SELECT * FROM book_artist WHERE art_id=" . $result4['art_id'];

It first gets a list from the art_assoc and then loops through each record doing a query on the book_artist using a value from the current record. Instead you just need one query to return all of the needed results. (Nested queries like that are horribly inefficient).

 

$query = "SELECT *
          FROM art_assoc
          JOIN book_artist ON art_assoc.art_id = book_artist.art_id
          WHERE song_id=" . $result3['song_id'];

 

You have a lot going on in your code and it would take me some time to digest it all. I'll see what I can do and post back. Comments in your code is always good practice - especial for situations such as this.

Link to comment
Share on other sites

One look at the code and I took the easy option :)

 

<?php
$songs = array(

    0 => array(
      'name' => "Baby, Please Don't Go",
      'artist' => array(
                    0 => "AC/DC"
                    )
    ),
    1 => array(
      'name' => "Tequila" ,
      'artist' => array(
                    0  => "A.L.T. and The Lost Civilization"
                    )
    ),
    2 => array(
      'name' => "Show You Love Me",
      'artist' => array(
                    0 => "A.K. Soul",
                    1 => "Jocelyn Brown"
                    )
    ),
    3 => array(
      'name' => "Dog Eat Dog",
      'artist' => array(
                    0 => "AC/DC"
                    )
    )
);

function mysort($a,$b) { return strcmp($a[artist][0], $b['artist'][0]); }

usort ($songs, 'mysort');

echo '<pre>', print_r($songs, true), '</pre>';
?> 

Link to comment
Share on other sites

all due respect for helping me out, but code doesn't help me unless there's an explaination with it. and i won't only be sorting by artist ill want to be sorting by other fields that are pulled from the book_songs table too, so Barand thanks very much for your help but unfort it doesn't help me alot :(

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.