【问题标题】:Filter array with specified conditions具有指定条件的过滤器数组
【发布时间】:2021-04-08 06:29:44
【问题描述】:

我有一个像这样的大数组:

[
"id" : "100",
"uuid": "7594873",
"parameters" => [
    "type" => "fast",
    "height" => "140"]
],[
"id" : "101"
"uuid": "7594872"
"parameters" => [
    "type" => "slow",
    "height" => "140"]
],[
"id" : "102",
"uuid": "7594875",
"parameters" => [
    "type" => "fast",
    "height" => "120"]
],[
"id" : "114",
"uuid": "7294876",
"parameters" => [
    "type" => "fast",
    "height" => "125",]
],[
"id" : "115",
"uuid": "7294123",
"parameters" => [
    "type" => "fast",
    "height" => "120",
    ]
]

我想返回(在 PHP 7 中)指定的结果,其条件与父级相同的类型参数和等于“120”的指定高度。

在这个例子中,数组结果应该是:

["7594873" => ["7594875", "7294123"]]

我应该使用 array_filter 吗?我在数组中有 100 000 条记录,我想尽快搜索。

【问题讨论】:

  • 你怎么知道哪些记录是父母,哪些是孩子?
  • 如果您使用var_export 来输出您的样本数据也会很有帮助;那么它可以直接读取为 PHP 用于测试目的。
  • foreach 比 array_filter 快,因为 array_filter 使用了闭包函数。
  • 所以也许 array_search 与 array_column?

标签: php arrays array-filter


【解决方案1】:

使用创建新数组的简单 foreach 的解决方案:

$type = $arr[0]['parameters']['type']; //or what is parent type ?

$result = [];
foreach($arr as $key => $row){
  if($row['parameters']['type'] != $type) continue;
  if($row['parameters']['height'] != 120) continue;
  if($row['id'] <= 100) continue;
  $result[$key] = $row;
}

在循环结构中跳过当前循环迭代的剩余部分,然后继续执行下一次迭代。

结果:

array (
  2 => 
  array (
    'id' => "102",
    'uuid' => "7594875",
    'parameters' => 
    array (
      'type' => "fast",
      'height' => "120",
    ),
  ),
  4 => 
  array (
    'id' => "115",
    'uuid' => "7294123",
    'parameters' => 
    array (
      'type' => "fast",
      'height' => "120",
    ),
  ),
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-05
    • 2019-10-25
    • 1970-01-01
    • 2019-03-02
    • 2021-12-10
    • 1970-01-01
    • 2016-02-07
    • 2019-11-20
    相关资源
    最近更新 更多