Mic
Mic

Reputation: 333

Deleting json array in php

I'm trying to delete an array from a JSON file using PHP.

I'm just unsure how to set delete an array using PHP. I can handle the jQuery side of things.

If I click a button on my front end, it will delete that array.

<button id="harry_0123">harry_0123</button>
<button id="ben_0124">ben_0124</button>

Here is an example of the JSON file:

{
    "harry_0123": {
        "id": "0123",
        "name": "harry",
    },
        "ben_0124": {
        "id": "0124",
        "name": "ben",
    },
}

Here is an example of my PHP:

<?php

    $json_str = file_get_contents('doc/info.json');


    $json_arr = json_decode($json_str, true);


    if(!$json_arr) {
        $json_arr = array();
    }

    $json_str_done = json_encode($json_arr, JSON_PRETTY_PRINT);
    file_put_contents('doc/info.json', $json_str_done);

Upvotes: 0

Views: 79

Answers (2)

Murzid
Murzid

Reputation: 91

Your JSON code should be (too many comma) :

{
  "harry_0123": {
    "id": "0123",
    "name": "harry"
  },
  "ben_0124": {
    "id": "0124",
    "name": "ben"
  }
}

To remove array data in PHP, you can use unset :

// Index Target (use $_POST / $_GET if you submitted from a form)
$target = 'harry_0123';

// Check Target
if ( isset($json_arr[$target]) ) {

    // Deleting
    unset($json_arr[$target]);
}

Upvotes: 1

M.Hemant
M.Hemant

Reputation: 2355

Try This,

if(!empty($json_arr)) {
      unset($json_arr['ben_0124'])
  }

Upvotes: 1

Related Questions