PHP和Json在nil属性中插入属性

时间:2013-09-19 11:54:00

标签: php json

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

$jsonContent = json_decode($content,true); 

$dicCurrentContent = $jsonContent[$dicRef];

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

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

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

我使用此代码:

$dicCurrentCours = $jsonContent['dicHistoriqueCours']; 

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

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

我得到一个Extra []]:

{"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":[]}

我该怎么办?

感谢所有人!

1 个答案:

答案 0 :(得分:0)

您只能添加非空数组:

foreach ($dicCours as $valueTemp) {
  if(!is_array($valueTemp) || !empty($valueTemp)) {
    $jsonContent['dicHistoriqueCours'][] = $valueTemp;
  } 
}