json encode is not working with array of objects

后端 未结 5 1500
故里飘歌
故里飘歌 2020-12-31 04:06

I want to convert array of objects to json encoding, I make like this

$allVisits = $mapper->getAllVisits($year, $month);
echo json_encode($allVisits);
         


        
5条回答
  •  天命终不由人
    2020-12-31 04:27

    For those who are looking for simple answer, unlike other complicated answers my is piece of art:

    json_encode(array(
        Protocol::PARAM_CODE => Protocol::CODE_SUCCESS,
        Protocol::PARAM_USER => (object)$user->jsonSerialize()
    ));
    

    Even when $user->jsonSerialize() outputs stdObject, json_encode is so dumb, it has no idea it is object so you have to state that explicitly with casting it to (object) - don't you love PHP for it's simplicity?

提交回复
热议问题