有一种方法可以做到这一点,即删除所有符合条件的项但是,如果你确定
一
与条件匹配的项,这是低效的,因为它评估
全部的
项目。
如果你想要这个“简单”的版本,你应该循环
$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