在php中使用array_intersect()实现二维数组

nzkunb0c  于 2023-03-28  发布在  PHP
关注(0)|答案(3)|浏览(118)

我正在尝试过滤满足两个条件的二维数组。但是,它没有按预期工作。我发现错误是在array_intersect()函数中。为什么array_intersect()在这里不能正确工作。有没有其他方法可以不迭代地完成这个任务?

<?php
            error_reporting(0);
            $students = [
                ["name"=> 'k. l.james', "grade"=>8],
                ["name"=> 'k. l.james', "grade"=>9],
                ["name"=> 'e. musk', "grade"=>8],
                ["name"=> 'jone', "grade"=>9],
            ];
        
            function filterByGrade($grade){
                global $students ;
                if (empty($grade)){
                    return $students ;
                }else{
        
                return array_filter($students , function($record) use($grade){
                    return ($record['grade'] == $grade);
                });
            }
            }
        
            function filterByName($name){
                global $students;
                if (empty($name)){
                    return $students;
                }else{
                
                return array_filter($students, function($record) use($name){
                    return (strcasecmp(str_replace(' ','',$record['name']),str_replace(' ','',$name)) == 0);
                });
            }
            }
            print_r(filterByGrade(8));
            echo "<br/>";
            print_r(filterByName('k.l.james'));
            echo '<br/>';
            print_r(array_intersect(filterByGrade(8), filterByName('k.l.james')));
        ?>

结果是;

Array ( [0] => Array ( [name] => k. l.james [grade] => 8 ) [2] => Array ( [name] => e. musk [grade] => 8 ) )
    Array ( [0] => Array ( [name] => k. l.james [grade] => 8 ) [1] => Array ( [name] => k. l.james [grade] => 9 ) )
    Array ( [0] => Array ( [name] => k. l.james [grade] => 8 ) [2] => Array ( [name] => e. musk [grade] => 8 ) )

我希望最后一行结果是,

Array ( [0] => Array ( [name] => k. l.james [grade] => 8 ))

如果我在array_intersect()中交换两个数组,结果是不同的。

print_r(array_intersect(filterByName('k.l.james'),filterByGrade(8)));

然后,我得到如下结果。

Array ( [0] => Array ( [name] => k. l.james [grade] => 8 ) [2] => Array ( [name] => e. musk [grade] => 8 ) )
    Array ( [0] => Array ( [name] => k. l.james [grade] => 8 ) [1] => Array ( [name] => k. l.james [grade] => 9 ) )
    Array ( [0] => Array ( [name] => k. l.james [grade] => 8 ) [1] => Array ( [name] => k. l.james [grade] => 9 ) )

我注意到,尽管考虑了两个数组的交集,但只打印了array_intersect()中的第一个过滤数组。

7dl7o3gd

7dl7o3gd1#

您可以创建一个函数来使用多个条件过滤学生,而不是尝试合并两个结果。
该功能:

/**
 * Here, $condition array of keys/values used to filter $data.
 * ex: ['name' => 'jone', 'grade' => 9]
 */
function filterArray($data, $conditions)
{
    if (empty($conditions)) {
        return $data;
    }
    
    return array_filter($data, function($record) use ($conditions) {
        // Check all given conditions
        foreach ($conditions as $key => $value) {
            // If doesn't match, return false (don't keep in filtered array)
            if ($record[$key] != $value) return false;
        }
        // conditions passed, add to array
        return true;
    });
}

使用方法:

$students = [
    ["name"=> 'k. l.james', "grade" => 8],
    ["name"=> 'k. l.james', "grade" => 9],
    ["name"=> 'e. musk', "grade" => 8],
    ["name"=> 'jone', "grade" => 9],
];

print_r(filterArray($students, ['grade' => 8]));
// out : [["name"=> 'k. l.james', "grade" => 8],["name"=> 'e. musk', "grade" => 8]]

print_r(filterArray($students, ['name' => 'k. l.james']));
// out : [["name"=> 'k. l.james', "grade" => 8], ["name"=> 'k. l.james', "grade" => 9]]

print_r(filterStudents($students, ['grade' => 8, 'name' => 'k. l.james']));
// out : [["name"=> 'k. l.james', "grade" => 8]]

补充说明:

  • 不鼓励使用global,在下面的代码中,$students由函数参数给出。
  • 在“return early”模式(if ($someCondition) { return; } else { })之后不需要使用else语句。
nwwlzxa7

nwwlzxa72#

array_intersect()函数正确,如果内部数组对象被序列化。

print_r(
    array_map('unserialize',
        array_intersect(
            array_map('serialize', filterByName('k.l.james')),
            array_map('serialize', filterByGrade(8))
        )
    )
);

我能知道什么是更有效的网站过滤器,@Syscall 的答案或我的方法。

c0vxltue

c0vxltue3#

一个简洁的解决方案是在array_filter()调用中调用array_intersect_assoc()--假设您有一个限定元素的平面关联数组。

$students = [
    ["name" => 'k. l.james', "grade" => 8],
    ["name" => 'k. l.james', "grade" => 9],
    ["name" => 'e. musk', "grade" => 8],
    ["name" => 'jone', "grade" => 9],
];

$filterBy = ["name" => 'k. l.james', "grade" => 8];

var_export(
    array_filter(
        $students,
        fn($row) => !array_intersect_assoc($filterBy, $row)
    )
);

实际上,给定行具有清空filterBy数组所需的关联数据,则应保留该行。

相关问题