Skip to content
Advertisement

Remove item from JSON returned from API

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

  1. Decode the data.
  2. Remove the item from the array.
  3. 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);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement