I’m new to PHP and have some trouble trying to delete an item from some data returned by an API
function getData() { $ch = curl_init($url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_POSTFIELDS, ""); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',)); $data = curl_exec($ch); echo $data; exit(); }
Here is the JSON data, I want to remove the item with Id 11
, how can I do this?
{ "Data": [ { "Id": 11, "Name": "Name1" }, { "Id": 12, "Name": "Name2" } ] }
Advertisement
Answer
- Decode the data.
- Remove the item from the array.
- Optionally encode it again as string if needed.
$dataArray = json_decode($data, true); foreach ($dataArray['Data'] as $key => $item) { if ($item['Id'] === 11) { unset($dataArray['Data'][$key]); } } $data = json_encode($dataArray);