2

I'm trying to delete specific key and value pair from external JSON file in PHP when user clicked delete button on the page.

I'm not familiar with PHP so I couldn't able to figure out what I'm doing wrong. I looked at more than 20 questions on stackoverflow but none of them helped to solve my problem.

What I'm trying to achieve in general to write a simple script which user can write something in textbox and submit, show it on the page and when user wants delete it. (I have done the submit and showing part but stuck on deleting part)

Firstly my JSON file:

{
"departman1":
[
{"departman1stage":"John"},
{"departman1stage":"Test"},
{"departman1stage":"Test2"}
]
}

Part of my index.php file:

    ...
    include ('yazdir.php');
    include ('sil.php');
    <div class='icerik'>
                    
    
                    <?php
                    
                    foreach ($json['departman1'] AS $d){
                        echo '<p class="' . $d['departman1stage'] .'">';
                        echo "--> ";
                        echo $d['departman1stage'];
                        echo '<form action="sil.php" method="POST"><button type="submit" class="dugme" name="' . $d['departman1stage'] .'"><i class="fa fa-trash"></i></button></form>';
                        echo "<br>";
                        echo "</p>";
                    }
                    ?>
                    </div>
                    <br>
                    <form action="yazdir.php" method="POST">
                    <div class="icerik"><p><input type="text" name="departman1stage"></p></div>
                    <br>
                    <input type="submit" value="Gonder">
                    </form>
...

It is not related with problem but I still put my yazdir.php code:

$json_sifreli = file_get_contents ("data.json");
$json = json_decode($json_sifreli, true);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
     $data = array(
        'departman1stage'          => $_POST["departman1stage"]
           );
       array_push ( $json['departman1'], $data );
        $json_sifreleme = json_encode($json, true);
       file_put_contents('data.json', $json_sifreleme);
}

sil.php is currently blank, as I said I tried different methods. Some of them deleted whole JSON file and put 'null' into it. Some of them deleted unrelated key and value pair. As a last resort, I decided to write here.

Thanks in advance, sorry for taking your time.

4
  • Does this answer your question? Delete element from json with php Commented Jan 2, 2021 at 22:55
  • @WOUNDEDStevenJones Hi, I saw and tried that answer by customizing it to me case. But it didn't work for me. No matter what GET value I gave, it deletes the first key value pair and deletes the array brackets. Commented Jan 2, 2021 at 23:32
  • I linked to that question because it explains how to delete keys using unset, which your code doesn't appear to do at all. Commented Jan 2, 2021 at 23:50
  • I think this question would be better if you posted the code that relates to the deletion part Commented Jan 3, 2021 at 0:12

1 Answer 1

4

You can delete keys using the PHP built-in unset function. It works on individual array keys:

<?php
$foo = [
    'a' => 23,
    'b' => 42,
];
unset($foo['a']);
var_dump($foo);

Results in:

array(1) {
  ["b"]=>
  int(42)
}

PHP arrays are hash maps, no matter if keys are strings are numeric. In your example JSON, departman1 is an array with numeric keys. You can delete numeric keys with unset as well:

$bar = [
    23,
    42,
];
unset($bar[0]);
var_dump($bar);

Results in:

array(1) {
  [1]=>
  int(42)
}

Note that the dump shows 1 as key. Unsetting numeric keys does not cause the array to be renumbered. You end up with holes and this will show up in json_encode output:

echo json_encode($bar);
// Results in: {"1":42}

So you could go through the swamp of using a JSON file as data store, but be cautioned it's a Pandoras Box full of hardships. It also doesn't scale beyond one concurrent user because json_encode and json_decode do not provide ACID properties, which database management systems provide you. My suggestion: ditch the JSON file and pick up a proper database such as PostgreSQL or MySQL (they have good support in PHP via PDO).

view the example code in playground

(BTW: You are using the $_POST variable directly, which is unsafe user input. Sanitizing input can be done with PHP built-in filter_var function.)

Sign up to request clarification or add additional context in comments.

1 Comment

Welcome to SO! Great first answer, hope to see more

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.