0

我有一个将属性插入 JSON 文件的脚本,为此我使用:

$jsonContent = json_decode($content,true); 

$dicCurrentContent = $jsonContent[$dicRef];

$jsonContent[$dicRef][] = $currentDic;

没问题,我可以设法在属性中添加新属性,我的问题是当属性为零时,就像这样:

{"dicHistoriqueCours":[],"dicHistoriqueDevoir":[],"dicHistoriqueInterroDone":[],"dicHistoriqueInterroCorrigee":[]}

我使用这段代码:

$dicCurrentCours = $jsonContent['dicHistoriqueCours']; 

foreach ($dicCours as $valueTemp)
{
  $jsonContent['dicHistoriqueCours'][] = $valueTemp; 
}

这给了我一个格式错误的 JSON 文件,因为我在“dicHistoriqueCours”属性的末尾得到了一个额外的 ]。

我得到一个额外的 []] :

{"dicHistoriqueCours":[{"Mati\u00e8re":"Fran\u00e7ais","intTotal":"10","Titre":"Le Pluriel","Type":"cours","Adresse":"lePluriel","Difficult\u00e9":"3","Prix":"free","intPoint":"7"},{"Mati\u00e8re":"Fran\u00e7ais","intTotal":"5","Titre":"Le Pass\u00e9 Compos\u00e9","Type":"cours","Adresse":"lePasseComp","Difficult\u00e9":"2","Prix":"free","intPoint":"2"},[]],"dicHistoriqueDevoir":[],"dicHistoriqueInterroDone":[],"dicHistoriqueInterroCorrigee":[]}

我能做些什么 ?

谢谢大家!

4

1 回答 1

0

您只能添加非空数组:

foreach ($dicCours as $valueTemp) {
  if(!is_array($valueTemp) || !empty($valueTemp)) {
    $jsonContent['dicHistoriqueCours'][] = $valueTemp;
  } 
}
于 2013-09-19T12:30:40.917 回答