如何在php中添加json格式的fabricjs-canvas对象的索引数组


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

我试图使一个数据库系统来处理保存的fabricjs画布。我需要画布对象

json=canvas.toDatalessJSON; // in javascript

…在PHP中保存为索引数组系统中的.json文件,允许我加载和添加更多的画布对象或删除对象。困扰我的是如何构建它。我在这里尝试的是:

... 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);

但这显然不是正确的做法。有什么想法吗?

编辑1 谢谢你的回答@Michael。我没有完全按照你的建议去做。但我接受它,因为它让我找到了一个解决方案。在我的解决方案中,我将索引添加到对象,并在我要使用对象时取消设置索引。

创建:

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

添加:

$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);

假设您正在尝试使用php覆盖json对象中的元素"1",请尝试:

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

如果你想添加一个元素:

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