1

认为,

$data = array(
   array('id' => 1, 'user_id' => 1, 'assignment_id' => 1, 'grade' => 90),
   array('id' => 2, 'user_id' => 3, 'assignment_id' => 2, 'grade' => 85),
   array('id' => 3, 'user_id' => 5, 'assignment_id' => 5, 'grade' => 66),
);

现在我想过滤如下行:

$rules = array(
    'user_id' => 5,
    'assignment_id' => 5
);

这应该返回$data[2].

$rules = array(
    'user_id' => 3,
    'assignment_id' => 2,
    'grade' => 85
);

将返回$data[1]

这里的 order of元素和keys可能不同。$data$rules

我试过了array_intersect,但这对我不起作用。

4

2 回答 2

3

如果您只需要返回$data与过滤条件匹配的元素列表,则可以使用array_filter()和的组合array_intersect_assoc()来完成这项工作:

// build an array of your filtering criteria
$filter_array = array(
   'user_id' => 3,
   'assignment_id' => 5
);

// filter the array
$filtered_array = array_filter($data, function ($val_array) use ($filter_array) {
    $intersection = array_intersect_assoc($val_array, $filter_array);
    return (count($intersection)) === count($filter_array);
});

请注意,您需要 PHP >= 5.3.0 才能使用所示的匿名函数。

于 2013-08-12T18:38:28.300 回答
1

这是一种更现代、更优雅的方法。

使用箭头函数语法允许$rules进入自定义函数的范围。如果在按每个遇到的行关联过滤规则数组后没有剩余元素,则满足所有规则。

代码:(演示

$data = [
   ['id' => 1, 'user_id' => 1, 'assignment_id' => 1, 'grade' => 90],
   ['id' => 2, 'user_id' => 3, 'assignment_id' => 2, 'grade' => 85],
   ['id' => 3, 'user_id' => 5, 'assignment_id' => 5, 'grade' => 66],
];

$rules = ['user_id' => 3, 'assignment_id' => 2];

var_export(
    array_filter($data, fn($row) => !array_diff_assoc($rules, $row))
);

输出:

array (
  1 => 
  array (
    'id' => 2,
    'user_id' => 3,
    'assignment_id' => 2,
    'grade' => 85,
  ),
)
于 2022-01-16T15:37:30.317 回答