【问题标题】:Php filtering arrayphp过滤数组
【发布时间】:2018-11-01 17:18:16
【问题描述】:

我必须为 PrestaShop 过滤一个数组。我有一些原始数据,但我必须对其进行过滤。所以我有一些原始数据搜索的输入,我尝试了很多方法,但我的老板仍然说有更好的方法。我不明白,所以我需要帮助。

<?php 
// Raw data
$data = array(
    array('id' => 1, 'name' => "Andrei", "time" => 3),
    array('id' => 5, 'name' => "David", "time" => 62),
    array('id' => 8, 'name' => "Igor", "time" => 12),
    array('id' => 4, 'name' => "Jack", "time" => 3),
);
// These are condition for filter my $data 
// In this condition i want filter my $data by name and time
$conditions = array('id' => null, 'name' => "David", 'time' => "3");
?>

问题是我的$condition 的所有组合过滤的最佳方式或方法是什么?

【问题讨论】:

标签: php arrays sorting filtering


【解决方案1】:

您应该使用回调查看array_filter

array_filter($data, function ($item) use ($conditions) {
    return $item['id'] === $conditions['id'] || $item['name'] === $conditions['name'] || $item['time'] === $conditions['time'];
}

您将需要根据您的预期过滤调整return 的验证。

【讨论】:

  • 您需要在函数中添加use($conditions),以便它可以访问变量。
  • 自从我使用 PHP(现在主要是一名 JavaScript 开发人员)以来,这已经很稳定了,即使我在积极使用它,我也总是忘记这样做。谢谢!
猜你喜欢
  • 2018-05-04
  • 1970-01-01
  • 2016-07-05
  • 2016-05-24
  • 1970-01-01
  • 2023-03-20
  • 2012-08-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多