Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.
public static function find_user_tracks($id)
{
    global $mySQL;
    $sql = "SELECT * FROM `tracks` WHERE account_id = {$id}";
    $result_set =  $mySQL->query($sql);
    $ret = array();
    while($row = $result_set->fetch_assoc()) 
    {
        $ret[] = $row;
    }
    return $ret;
} 

The above code contains the result of a database query. The database looks like this:

database screenshot

So basically it will return to me a set of fields with values and then I'll get those values to use them for a certain page:

$row = Track::find_user_tracks($id);
if(!empty($row))
{
    $track_paths = array();
    $track_names = array();
    $track_desc = array();
    $track_ids = array();
    $track_artist = array();
    for($i = 0 ;$i<count($row);$i++)
    {
        $track_paths[] = $row[$i]['track_path'];
        $track_ids[] = $row[$i]['track_id'];
        $track_names[] = $row[$i]['track_name'];
        $track_desc[] = $row[$i]['track_desc'];
        $track_artist[] = $row[$i]['artist'];
    }
    echo "<h1> {$screename}'s Beats</h1>";
}

The $row variable contains the result from the previous queries. I loop over $row to extract every single bit of data like track_id, track_name, etc.

Now I am wondering: is there any way to make this cleaner or improve it?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

I think this will work. You'll have to have PHP version 5.3 though, otherwise you'll have to remove the lambda functions and define actual functions in their place. Disclaimer, not to say that this is easier to read or easier to understand, but I think it fits the "cleaner" request.

$track_paths = array_map( function ( $array ) { return $array[ 'track_path' ]; }, $row );
$track_ids = array_map( function ( $array ) { return $array[ 'track_id' ]; }, $row );
$track_names = array_map( function ( $array ) { return $array[ 'track_name' ]; }, $row );
$track_desc = array_map( function ( $array ) { return $array[ 'track_desc' ]; }, $row );
$track_artist = array_map( function ( $array ) { return $array[ 'track_artist' ]; }, $row );
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.