Reputation: 411
I Have a files.json with content:
[
{
"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\/"
}
]
How to remove item with multiple condition in PHP and return other items if: fileName = "product1.zip" & restoreDir = "Files/Archives1/" and save again into files.json
Expected Result in 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\/"
}
]
Thanks,
Upvotes: 0
Views: 53
Reputation: 22773
Here's one way to do it, that removes all items that match the criteria. However, if you're sure there's only ever going to be one item that match the criteria, this is inefficient, because it evaluates all items.
If you want this "simpler" version, you should just loop though $decoded
(with a for( ; ; )
or foreach()
) and as soon as the criteria are met, remove the item from the array and break
out of the loop.
$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 );
Upvotes: 1