note 88790 added to function.json-encode
| From: | aangel at spam dot com | Date: | Sun, 08 Feb 2009 01:50:35 +0000 |
| Subject: | note 88790 added to function.json-encode | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-150373@lists.php.net to get a copy of this message | ||
Here is a bit more on creating an iterator to get at those pesky private/protected variables:
<?php
class Kit implements IteratorAggregate {
public function __construct($var) {
if (is_object($var)) {
// if passed an object, we are cloning
$this->kitID = $var->kitID;
$this->kitName = $var->kitName;
foreach ($var->productArray as $key => $value) {
$this->productArray[$key] = (array)$value;
}
}
}
...
// Create an iterator because private/protected vars can't
// be seen by json_encode().
public function getIterator() {
$iArray['kitID'] = $this->kitID;
$iArray['kitName'] = $this->kitName;
$iArray['productArray'] = (array)$this->productArray;
return new ArrayIterator($iArray);
}
}
?>
Calling something like $t = json_encode($this->getIterator()); will give you almost what you
want:
<?php
{"kitID":"Kit_Essentials-Books.txt",
"kitName":"Essential Books",
"productArray":{"0470043601":{"Category":"Food","ASIN":"0470043601"}
} }
?>
Notice that the productArray is converted to an object ignoring the cast I put in front, which is
not what I wanted. I haven't figured out how to make sure that encodes as an array.
Regardless, bringing that JSON back into an object using json_decode() will give you just a std
object, and the only way I've found to get it into the proper object type is to use a
constructor that instantiates the object the way it's supposed to be (see __construct($var)
above). Like this:
<?php
$newKit = new Kit(json_decode($t));
?>
----
Server IP: 69.147.83.197
Probable Submitter: 71.202.92.140
----
Manual Page -- http://www.php.net/manual/en/function.json-encode.php
Edit -- https://master.php.net/note/edit/88790
Del: integrated -- https://master.php.net/note/delete/88790/integrated
Del: useless -- https://master.php.net/note/delete/88790/useless
Del: bad code -- https://master.php.net/note/delete/88790/bad+code
Del: spam -- https://master.php.net/note/delete/88790/spam
Del: non-english -- https://master.php.net/note/delete/88790/non-english
Del: in docs -- https://master.php.net/note/delete/88790/in+docs
Del: other reasons-- https://master.php.net/note/delete/88790
Reject -- https://master.php.net/note/reject/88790
Search -- https://master.php.net/manage/user-notes.php