当前位置:Gxlcms > PHP教程 > php比较两二维数组求大神指教

php比较两二维数组求大神指教

时间:2021-07-01 10:21:17 帮助过:6人阅读

如:

$grade = Array
(
    [0] => Array
        (
            [course_name] => 大学英语(综合)-1
            [course_strid] => College English (Comprehensive)-1
            [credit] => 2
            [course_nature] => 必修
            [grade] => 70.0
            [year] => 2013-2014
            [term] => 1
            [user_id] => 1034
        )
)

$temp = Array
(
    [0] => Array
        (
            [user_id] => 1034
            [year] => 2013-2014
            [term] => 1
            [course_name] => 大学英语(综合)-1
            [course_nature] => 必修
            [credit] => 3
            [grade] => 1
            [course_strid] => 1
        )
)

$grade为准 若两个数组只要有不同 就返回$grade的数组

回复内容:

如:

$grade = Array
(
    [0] => Array
        (
            [course_name] => 大学英语(综合)-1
            [course_strid] => College English (Comprehensive)-1
            [credit] => 2
            [course_nature] => 必修
            [grade] => 70.0
            [year] => 2013-2014
            [term] => 1
            [user_id] => 1034
        )
)

$temp = Array
(
    [0] => Array
        (
            [user_id] => 1034
            [year] => 2013-2014
            [term] => 1
            [course_name] => 大学英语(综合)-1
            [course_nature] => 必修
            [credit] => 3
            [grade] => 1
            [course_strid] => 1
        )
)

$grade为准 若两个数组只要有不同 就返回$grade的数组

查了下,貌似这个函数可以满足要求:
http://www.w3school.com.cn/php/func_array_diff_assoc.asp

如果楼主给的数组结构和问题中给的一模一样。那么可以用以下方法:

function compare($grade,$temp)
{
    $compare = array_diff_assoc($grade[0],$temp[0]);
    if ($compare != null) {
        return $grade;
    }
}

如果$grade下面实际包含很多子数组,不止$grade[0]这一个,那么结合楼上的方法:

function compare($grade,$temp)
{
    foreach($grade as $key=>$value){
        $compare = array_diff_assoc($value,$temp[$key]);
        if ($compare != null) {
            return $grade;
        }
    }

}

如果解决了你的问题记得采纳 :)

phpforeach($grade as $key=>$item){
    if($item != $temp[$key]){
        return false;
    }
}
return true;

foreach简单,高手来个优雅的方法!

人气教程排行