foreach用sql选择获取数组

时间:2013-12-20 03:32:20

标签: php sql arrays

我的智能脚本工作,我的新PHP代码遇到了一些问题..

我只需要隐藏基于IP的访客观看的视频,我试试这个..

 //-- Get visitor ip

    if (!empty($_SERVER['HTTP_CLIENT_IP'])){   //check ip from share internet
        $visitor_ip=$_SERVER['HTTP_CLIENT_IP'];
    }elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){ //to check ip is pass from proxy
        $visitor_ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }else{
        $visitor_ip=$_SERVER['REMOTE_ADDR'];
    }//Get ip


if ( !empty ($visitor_ip) ){            
        $sql_query = "SELECT vid_id FROM videos_watched WHERE ip=(INET_ATON('$visitor_ip'))";
        $result_videos_watched = $GLOBALS["DB"]->result( $sql_query );
    }

        foreach ($result_videos_watched as $vid_id_watched){

            $videos_watched[] = $vid_id_watched;
        }


    $sql_query = "SELECT vid_id FROM videos WHERE mem_id=".$entry["mem_id"]." ".$GLOBALS["Videos"]->filter();


    foreach($videos_watched as $v_watched) {

        $sql_query.= " AND vid_id != ".$v_watched;
    }


    $sql_query.= " AND vid_id != ".$vid_id." ORDER BY posted DESC LIMIT 0,5";

    $result = $GLOBALS["DB"]->result( $sql_query );

我得到一个$ v_watched = array !!

提前致谢

1 个答案:

答案 0 :(得分:0)

$result_videos_watched是一个二维数组。第一个维度是结果的行,第二个维度是列。当你这样做时:

foreach ($result_videos_watched as $vid_id_watched){

$vid_id_watched是结果行之一,因此它是列的数组。然后当你这样做:

$videos_watched[] = $vid_id_watched;

您正在为该数组设置$videos_watched的新元素。所以videos_watched变成了一个二维数组(它只是$result_videos_watched的副本)。我想你想做的是:

$videos_watched[] = $vid_id_watched['vid_id'];

作为建议,请使用vid_id !=,而不是让新查询进行一系列vid_id NOT IN (...)次测试。我希望大多数SQL引擎能够更好地优化它。