0

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);
4
  • You mean, if you clicked on ben_0124 id button then from info.json ben_0124 array will be deleted? and harry_0123 will remain as it is? Commented Mar 18, 2019 at 3:40
  • yes exactly. im just looking to remove a json array with php. Commented Mar 18, 2019 at 3:45
  • ok so, did you write any ajax in your HTML portion to pass your button id to your PHP file? if yes then show us that code with echo var_dump($_POST) that data Commented Mar 18, 2019 at 3:50
  • that would require me to rewrite it here. here is something im working. if(!$json_arr) { unset(array["ben_0124"]); $json_arr = array(); } this how ever is not working. Commented Mar 18, 2019 at 4:04

2 Answers 2

1

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]);
}
Sign up to request clarification or add additional context in comments.

Comments

1

Try This,

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.