tags:

views:

43

answers:

3

Hello guys,

I have two associative arrays in PHP that are defined as following:

$this_week[] = array(
        "top_song_id" => $row["view_song_id"],
        "top_place" => $i, 
        "top_move" => "0",
        "top_last" => $i,
        "top_peak" => $i,
        "top_rating" => get_song_rating_by_id($row["view_song_id"]),
        "top_views" => $row["view_sum"],
        "top_start" => $monday,
        "top_end" => $sunday         
        );

and

$last_week[] = array(
        "top_song_id" => $row["view_song_id"],
        "top_place" => get_song_place_by_id($row["view_song_id"]), 
        "top_move" => "0",
        "top_last" => get_song_last_by_id($row["view_song_id"]),
        "top_peak" => get_song_peak_by_id($row["view_song_id"]),
        "top_rating" => get_song_rating_by_id($row["view_song_id"]),
        "top_views" => $row["view_sum"],
        "top_start" => $prev_monday,
        "top_end" => $prev_sunday            
        );

Now here is my question: how can I traverse this two arrays and perform an action if there is any song id in one array that can be found in the other one?

A for() loop doesn't work because there can be common songs for both arrays but not on the same array index.

Any help is appreciated.

A: 
if( in_array( $this_week["top_song_id"], $last_week ) ) {
    //do something
}
lemon
+1  A: 

An efficient way to do this is to just change the first line of the last snippet this way:

$last_week[$row["view_song_id"]] = array(    // Added the song id as the array index
    "top_song_id" => $row["view_song_id"],
...

After that you can use a simple for loop this way:

for ($this_week as $item) {
    if ( isset ($last_week[ $item["top_song_id"] ]) ) {
        // HERE YOU HAVE FOUND A DUPLICATE
    }
}
Andrea Zilio
A: 

Why not just hardcode the 5(?) comparisons you need in one if statement? No need to overcomplicate things.

NA