在特定子阵列中仅保留前10个记录



我有一些JSON,具有以下格式:

{
  "mainKey": [
    {
      "ID": "1018",
      "dish": "Fish",
      "desert": "Ice cream",
      "drink": "Cola"
    },
    {
      "ID": "1019",
      "dish": "Pizza",
      "desert": "Cake",
      "drink": "Water"
    },
    ...
  ],
  "anotherKey": [
    {
      "something": "something",
      "something": 123,
      "something": 123
    },
    ...
  ],
  ...
}

有很多键和很多数据,我已经缩短了它以显示基本结构。此JSON在一个称为$response的变量中。我首先将其转换为一个数组:

$response = json_decode($response, true);

我需要几个unset的键,所以我只是循环阵列一个未设置的数组:

foreach ($response as $key => $value) {
    if($key === 'mainKey') {
    }
    unset($response['another_key']);
    unset($response['yet_another_key']);
}

我并不是要摆脱所有钥匙,只有一对。我现在要做的是在mainKey上工作,这就是为什么我在循环中包含了IF语句。

如何仅保留mainKey的前10个记录?我看过诸如splice之类的东西,但是这会保留我数组中的其他键吗?这也可以保留我的索引,因为这些对我很重要?

考虑到mainKey的记录超过100K,最有效的方法是什么?

无需循环;功能可以以非常干净和简洁的方式完成这项工作。

代码:(演示(

$black_keys = array_flip(['another_key', 'yet_another_key']);    // blacklist
$array = array_diff_key(json_decode($json, true), $black_keys);  // decode and filter
$array['mainKey'] = array_slice($array['mainKey'], 0, 10);       // truncate mainKey subarray
var_export($array);

另外,这将表现稍好:

$array = json_decode($json, true);
unset($array['another_key'], $array['yet_another_key']);
$array['mainKey'] = array_slice($array['mainKey'], 0, 10);

由于mainKey将具有基于数值的键,因此您可以创建一个过滤器,该过滤器将删除所有落在给定范围之外的项目。

<?php
$json = '{
  "mainKey": [
    {
      "ID": "1018",
      "dish": "Fish",
      "desert": "Ice cream",
      "drink": "Cola"
    },
    {
      "ID": "1019",
      "dish": "Pizza",
      "desert": "Cake",
      "drink": "Water"
    }
  ],
  "anotherKey": [
    {
      "ID": "something",
      "dish": "123",
      "desert": "123"
    }
  ]
}';
$response = json_decode($json, true);
// If needed, unset your keys 
unset($response['anotherKey']);    
...
// Now, let's work only with `mainKey`
$mainKey = $response['mainKey'];
// Create a range of keys to keep
$allowed  = range(0, 10);
// Finally, filter out all keys not in the range you specified.
$filtered = array_filter(
    $mainKey,
    function ($key) use ($allowed) {
        return in_array($key, $allowed);
    },
    ARRAY_FILTER_USE_KEY
);
// `$filtered` now only has keys 0-10. 
var_dump($filtered);

最新更新