如何从 php 中的一个数组中删除另一个数组?

How do I remove one array from another in php?

我在 PHP 中有以下数组: print_r($员工) =

Array
(
    [0] => Array
        (
            [p_id] => T29083999
            [name] => Robert Plaxo
        )

    [1] => Array
        (
            [p_id] => T29083388
            [name] => Yvan Sergei
        )

    [2] => Array
        (
            [p_id] => T21083911
            [name] => Rhonda Saunders
        )

    [3] => Array
        (
            [p_id] => H02910382
            [name] => Miguel Mercado
        )
)

然后这个数组: print_r($记录) =

Array
(
    [0] => Array
        (
            [c_id] => 1
            [section] => 1061
            [term] => 201631
            [p_id] => T29083388
            [c_date] => 2016-04-01 09:14:00
        )

)

我想从 $employees 中删除与 $record 的 p_id 匹配的数组元素。数组 $record 可能有多个条目,如图所示。如果是这样,则必须从 $employees 中删除 $record 中的任何 p_id。

我试过:

foreach ($employees as $k => $e) {
    foreach ($record as $r) {
        if ($e['p_id']==$r['p_id']) {
            echo "found it!";
            // if I uncomment the next line, it crashes! (500 server error)
            //  unset $employees[$k];
        }           
    }   
}

我只想从 $employees 中删除任何元素,该元素具有与 $record 中的任何记录与该员工 ID 匹配的任何员工。

你快到了;只需要在 unset()

周围加上括号

我还冒昧地更改了一些变量名,因为单字符变量名让我很烦。

$employees[] = [
    'p_id' => 'T29083999',
    'name' => 'Robert Plaxo',
];
$employees[] = [
    'p_id' => 'T29083388',
    'name' => 'Yvan Sergei',
];
$employees[] = [
    'p_id' => 'T21083911',
    'name' => 'Rhonda Saunders',
];
$employees[] = [
    'p_id' => 'H02910382',
    'name' => 'Miguel Mercado',
];

$records[] = [
        'c_id' => '1',
        'section' => '1061',
        'term' => '201631',
        'p_id' => 'T29083388',
        'c_date' => '2016-04-01 09:14:00',
];

foreach ($employees as $key => $employee) {
    foreach ($records as $record) {
        if ($employee['p_id'] == $record['p_id']) {
            echo "found it!";
            unset($employees[$key]);
        }
    }
}

echo "<pre>";
print_r($employees);

产出

found it!

Array
(
    [0] => Array
        (
            [p_id] => T29083999
            [name] => Robert Plaxo
        )

    [2] => Array
        (
            [p_id] => T21083911
            [name] => Rhonda Saunders
        )

    [3] => Array
        (
            [p_id] => H02910382
            [name] => Miguel Mercado
        )

)

使用 array_columnarray_filter 函数的简短解决方案。它也将满足您的要求 "Array $record may have multiple entries":

$p_ids = array_column($record, "p_id");
$employees = array_filter($employees, function($v) use($p_ids){
    return !in_array($v["p_id"], $p_ids);     
});

print_r($employees);

输出:

Array
(
    [0] => Array
        (
            [p_id] => T29083999
            [name] => Robert Plaxo
        )

    [2] => Array
        (
            [p_id] => T21083911
            [name] => Rhonda Saunders
        )

    [3] => Array
        (
            [p_id] => H02910382
            [name] => Miguel Mercado
        )
)