Flemming Flemming - 2 months ago 13
PHP Question

How do i add fabricjs-canvas objects in json format to a indexed array in php?

I'm trying to make a database system to handle the saved fabricjs canvases. For every thing to work i need the canvas objects

json=canvas.toDatalessJSON; // in javascript


...to be saved in php as .json file in a indexed array system that allows me to load and add more canvas objects or delete objects.
The thing troubling me is how to actually structuring this. What i'm trying here is something like:

... The json structure i'm considering ...
["1"]{Object:.....}
["2"]{Object:.....}
["4"]{Object:.....} (["3"] deleted in this case)

... Trying to create in php ...
$i="1";
$A=[];
$A[$i]=[];
array_push($A[$i],json_decode($json));
$newjson=json_encode($A);


But this is obviously not the way to make it. Any ideas ?

EDIT 1
Thank's for your answaer @Michael. I ended up not using exactly what you propose. But i accept it as the answer that let my to a solution. In my solution i'm adding the index to the object, and unset the index when i'm going to use the object.

Create:

$dataA=array();
$dataB=json_decode($data,true);
$dataB["index"]= $ThumbIndex;
$dataA[]=&$dataB;
$data=json_encode($dataA);
file_put_contents($filename.'.json',$data);


Add:

$data0=file_get_contents($filename.'.json');
$dataA=json_decode($data0,true);
$dataB=json_decode($data,true);
$dataB["index"]= $ThumbIndex;
$dataA[]=&$dataB;
$data=json_encode($dataA);
file_put_contents($filename.'.json',$data);

Answer

Assuming you are trying to overwrite element "1" in your json object using php, try this:

$newjson = json_decode($json, true);    
$newjson["1"] = Array();    
$newjson = json_encode($newjson);

If you want to add an element:

$newjson = json_decode($json, true);    
$newjson[] = Array();
$newjson = json_encode($newjson);
Comments