From a5505c000c5b18833ea255f58136eb9349495f8d Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 20 Apr 2016 21:33:24 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=B9=E8=BF=9BModel=E7=B1=BB=E7=9A=84toArra?= =?UTF-8?q?y=E6=96=B9=E6=B3=95=20=E6=94=AF=E6=8C=81=E5=85=B3=E8=81=94?= =?UTF-8?q?=E6=A8=A1=E5=9E=8B=E8=BE=93=E5=87=BA=E6=95=B0=E7=BB=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index c93a86e0..8ce29278 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -119,7 +119,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess // JsonSerializable public function jsonSerialize() { - return $this->data; + return $this->toArray(); } // ArrayAccess @@ -178,7 +178,21 @@ abstract class Model implements \JsonSerializable, \ArrayAccess */ public function toArray() { - return !empty($this->data) ? $this->data : []; + $item = []; + foreach ($this->data as $key => $val) { + if ($val instanceof Model) { + $item[$key] = $val->toArray(); + } elseif (is_array($val) && $val[0] instanceof Model) { + $data = []; + foreach ($val as $k => $value) { + $data[$k] = $value->toArray(); + } + $item[$key] = $data; + } elseif (is_scalar($val)) { + $item[$key] = $val; + } + } + return !empty($item) ? $item : []; } /** @@ -912,7 +926,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess public function __toString() { - return json_encode($this->data); + return json_encode($this->toArray()); } /**