note 76215 added to function.json-encode
| From: | php at mikeboers dot com | Date: | Thu, 05 Jul 2007 14:49:32 +0000 |
| Subject: | note 76215 added to function.json-encode | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-128249@lists.php.net to get a copy of this message | ||
Here is a way to convert an object to an array which will include all protected and private members
before you send it to json_encode()
<?php
function objectArray( $object ) {
if ( is_array( $object ))
return $object ;
if ( !is_object( $object ))
return false ;
$serial = serialize( $object ) ;
$serial = preg_replace( '/O:\d+:".+?"/' ,'a' , $serial ) ;
if( preg_match_all( '/s:\d+:"\\0.+?\\0(.+?)"/' , $serial, $ms, PREG_SET_ORDER
)) {
foreach( $ms as $m ) {
$serial = str_replace( $m[0], 's:'. strlen( $m[1] ) . ':"'.$m[1] .
'"', $serial ) ;
}
}
return @unserialize( $serial ) ;
}
// TESTING
class A {
public $a = 'public for a' ;
protected $b = true ;
private $c = 123 ;
}
class B {
public $d = 'public for b' ;
protected $e = false ;
private $f = 456 ;
}
$a = new A() ;
$a -> d = new B() ;
echo '<pre>' ;
print_r( $a ) ;
print_r( objectArray( $a )) ;
?>
Cheers!
mike
----
Server IP: 69.147.83.197
Probable Submitter: 99.247.248.117
----
Manual Page -- http://www.php.net/manual/en/function.json-encode.php
Edit -- https://master.php.net/note/edit/76215
Del: integrated -- https://master.php.net/note/delete/76215/integrated
Del: useless -- https://master.php.net/note/delete/76215/useless
Del: bad code -- https://master.php.net/note/delete/76215/bad+code
Del: spam -- https://master.php.net/note/delete/76215/spam
Del: non-english -- https://master.php.net/note/delete/76215/non-english
Del: in docs -- https://master.php.net/note/delete/76215/in+docs
Del: other reasons-- https://master.php.net/note/delete/76215
Reject -- https://master.php.net/note/reject/76215
Search -- https://master.php.net/manage/user-notes.php