【问题标题】:Remove Item from Json File With multiple condition in PHP在 PHP 中使用多个条件从 Json 文件中删除项目
【发布时间】:2018-12-29 21:41:40
【问题描述】:

我有一个 files.json 内容:

[
  {
    "fileName": "product1.zip",
    "fileSize": "5.08 KB",
    "restoreDir": "Files\/Archives1\/"
  },
  {
    "fileName": "product1.zip",
    "fileSize": "1.39 MB",
    "restoreDir": "Files\/Archives2\/"
  },
  {
    "fileName": "product2.zip",
    "fileSize": "1.38 MB",
    "restoreDir": "Files\/Archives1\/"
  },
  {
    "fileName": "product2.zip",
    "fileSize": "1.37 MB",
    "restoreDir": "Files\/Archives2\/"
  }
]

如何在 PHP 中删除具有多个条件的项目并返回其他项目 if: fileName = "product1.zip" & restoreDir = "Files/Archives1/" 并再次保存到 files.json

files.json 中的预期结果:

[
      {
        "fileName": "product1.zip",
        "fileSize": "1.39 MB",
        "restoreDir": "Files\/Archives2\/"
      },
      {
        "fileName": "product2.zip",
        "fileSize": "1.38 MB",
        "restoreDir": "Files\/Archives1\/"
      },
      {
        "fileName": "product2.zip",
        "fileSize": "1.37 MB",
        "restoreDir": "Files\/Archives2\/"
      }
    ]

谢谢,

【问题讨论】:

  • 尝试获取并重写 .json 文件,满足条件

标签: php arrays json multidimensional-array stdclass


【解决方案1】:

这是一种方法,即删除所有符合条件的项目。但是,如果您确定只有 一个 项符合条件,那么这是低效的,因为它会评估 所有 项。

如果你想要这个“更简单”的版本,你应该只循环$decoded(使用for( ; ; )foreach()),一旦满足条件,从数组中删除该项目并break跳出循环。

$json = <<<'JSON'
[
  {
    "fileName": "product1.zip",
    "fileSize": "5.08 KB",
    "restoreDir": "Files\/Archives1\/"
  },
  {
    "fileName": "product1.zip",
    "fileSize": "1.39 MB",
    "restoreDir": "Files\/Archives2\/"
  },
  {
    "fileName": "product2.zip",
    "fileSize": "1.38 MB",
    "restoreDir": "Files\/Archives1\/"
  },
  {
    "fileName": "product2.zip",
    "fileSize": "1.37 MB",
    "restoreDir": "Files\/Archives2\/"
  }
]
JSON;

$criteria = [
  'fileName'   => 'product1.zip',
  'restoreDir' => 'Files/Archives1/'
];

$decoded = json_decode( $json, true );
$filtered = array_filter( $decoded, function( $item ) use ( $criteria ) {
  return array_intersect_assoc( $criteria, $item ) !== $criteria;
} );
$result = json_encode( $filtered, JSON_PRETTY_PRINT );

var_dump( $result );

view parsed online @ eval.in

【讨论】:

    猜你喜欢
    • 2020-09-05
    • 2021-11-10
    • 1970-01-01
    • 2023-04-06
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-22
    相关资源
    最近更新 更多