繁体   English   中英

在两个PHP数组中查找相同值时执行操作

[英]Performing an action when finding same values in two PHP arrays

我在PHP中有两个关联数组,其定义如下:

$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            
        );

$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           
        );

现在是我的问题:如果一个数组中有任何歌曲ID可以在另一个数组中找到,我该如何遍历这两个数组并执行操作?

for()循环不起作用,因为两个数组可以有共同的歌曲,但不在同一数组索引上。

任何帮助表示赞赏。

一种有效的方法是只更改最后一个片段的第一行:

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

之后,您可以通过以下方式使用简单的for循环:

for ($this_week as $item) {
    if ( isset ($last_week[ $item["top_song_id"] ]) ) {
        // HERE YOU HAVE FOUND A DUPLICATE
    }
}
if( in_array( $this_week["top_song_id"], $last_week ) ) {
    //do something
}

为什么不只在一个if语句中硬编码所需的5(?)比较? 无需过于复杂。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM