joysdepraved joysdepraved - 1 year ago 56
JSON Question

Removing a JSON record from .json file with PHP

I have a json file looking like this :


What I am trying to do is to remove a record from it by it's
. For this purpose I have the following PHP code :

$string = file_get_contents("products.json");
$json_a = json_decode($string, true); //turning JSON-string into an array containing JSON-strings

$arr = array();
foreach ($json_a as $key) {
array_push($arr,json_decode($key[0],true)); //and here you turning each of the JSON-strings into objects themselves

$data= $_GET['data'];
foreach($arr as $element) {
if($data == $element["id"]){
unset($arr[$i]);//removing the product by ID

$arr2 = array();

foreach ($arr as $key) {//trying to make it look like the original json.
echo json_encode($arr2);

What I am getting from this code is :

array(2) { [0]=> array(4) { ["id"]=> float(1474721566304) ["name"]=> string(3) "GGG" ["brand"]=> string(2) "GG" ["price"]=> string(1) "3" } [1]=> array(4) { ["id"]=> float(1474721570904) ["name"]=> string(4) "GGGH" ["brand"]=> string(3) "GGH" ["price"]=> string(1) "4" } }

I am really out of ideas how to make this array look like my original JSON shown first on this post. I tried many different things, but I couldn't make it work. My idea is after removing the record by it's ID to replace the old JSON with the new one that I am trying to construct here.

I am new to php and I'd appreciate any input on my issue.

Answer Source

First of all - your input JSON is wrong:

array (size=3)
  0 => 
    array (size=1)
      0 => string '{"id":1474721566304,"name":"GGG","brand":"GG","price":"3"}' (length=58)
  1 => 
    array (size=1)
      0 => string '{"id":1474721570904,"name":"GGGH","brand":"GGH","price":"4"}' (length=60)
  2 => 
    array (size=1)
      0 => string '{"id":1474721574188,"name":"GGGH","brand":"GGHH","price":"5"}' (length=61)

You don't have 'id' nor 'name', 'GGG' and other keys. You just have one long string. You should remove unnecessary quotation marks. After that your JSON should look like this:


And finally, your PHP code can be much shorter:

$json = "[[{\"id\":1474721566304,\"name\":\"GGG\",\"brand\":\"GG\",\"price\":\"3\"}],[{\"id\":1474721570904,\"name\":\"GGGH\",\"brand\":\"GGH\",\"price\":\"4\"}],[{\"id\":1474721574188,\"name\":\"GGGH\",\"brand\":\"GGHH\",\"price\":\"5\"}]]";
$input = json_decode($json, true);
$output = array();
foreach($input as $element) { //you don't need to declare yet another array, just use the one you already have
    if($_GET['data'] != $element[0]["id"]){ //and not unset, just add to new array if you want
       $output[] = $element; //shorter and faster than array_push()
echo json_encode($output);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download