我使用Doctrine作为ORM。我对此非常陌生。所以我希望发送实体的Json响应。实体如下:
Medicine and Generics有很多关系,Generic和Content也有很多关系。我需要展示药物的细节以及药物的仿制药和仿制药的内容。
这是我的代码
public function jsonSerialize()
{
$newArray= array();
$generics=$this->getGenerics();
foreach ($generics as $generic){
$array = json_decode(json_encode($generic), true);
var_dump($array);
array_push($newArray, $array);
}
var_dump($newArray);
$xyz=array();
$xyz1=array();
$arratJosn = array(
'medicineId' => $this->id,
'medicineName' => $this->medicineName,
'medicineQuantity' => $this->medicineQuantity,
'medicinePrice' =>$this->medicinePrice,
'manufactureId' =>$this->manufactureId->getmanufatureName(),
'medicineApproved' => $this->medicineApproved,
'medicineVersion' =>$this->medicineVersion,
'genericDetails'=> array('genericName'=>$xyz,
'genericQuantity' => $xyz1,),
);
foreach ($generics as $generic){
$genericName=$generic->getGenericName();
array_push($arratJosn['genericDetails']['genericName'], $genericName);
$contents=$generic->getContent();
foreach ($contents as $content){
$genericQuantity=$content->getGenericQuantity();
array_push($arratJosn['genericDetails']['genericQuantity'], $genericQuantity);
$genericPrice=$content->getGenericUnit();
}
}
return $this;
}
在实体上使用jsonEncode我能够检索json数据,如下所示:
{"medicineId":27,
"medicineName":"MedTest11",
"medicineQuantity":20
"medicinePrice":70,
"manufactureId":"Company2",
"medicineApproved":1,
"medicineVersion":1,
"genericDetails":{"genericName":["paracetamol","newgeneric"],
"genericQuantity":["30","40"]}
}
虽然我希望结果显示为
{"medicineId":27,
"medicineName":"MedTest11",
"medicineQuantity":20,
"medicinePrice":70,
"manufactureId":"Company2",
"medicineApproved":1,
"medicineVersion":1,
"genericDetails":[{"genericName":"paracetamol", "genericQuantity":"30"},{"genericName":"newgeneric", "genericQuantity":"40"}]
}
我怎样才能实现这个目标?
答案 0 :(得分:0)
要实现这一点,您需要将数组推送到像这样的通用详细信息
$arratJosn = array(
'medicineId' => $this->id,
'medicineName' => $this->medicineName,
'medicineQuantity' => $this->medicineQuantity,
'medicinePrice' =>$this->medicinePrice,
'manufactureId' =>$this->manufactureId->getmanufatureName(),
'medicineApproved' => $this->medicineApproved,
'medicineVersion' =>$this->medicineVersion,
'genericDetails'=> array()
);
foreach ($generics as $generic){
$genericName=$generic->getGenericName();
$contents=$generic->getContent();
foreach ($contents as $content){
$genericQuantity=$content->getGenericQuantity();
$genericPrice=$content->getGenericUnit();
$genericArray = array (
'genericName' => $genericName,
'genericQuantity' => $genericQuantity
);
array_push($arratJosn['genericDetails'],$genericArray);
}
}