note 128221 added to function.json-decode
| From: | greaties at ghvernuft dot nl | Date: | Tue, 14 Feb 2023 15:42:30 +0000 |
| Subject: | note 128221 added to function.json-decode | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-220177@lists.php.net to get a copy of this message | ||
To load an object with data in json format:
(bugfixed my previous comment)
<?php
function loadJSON($Obj, $json)
{
$dcod = json_decode($json);
$prop = get_object_vars ( $dcod );
foreach($prop as $key => $lock)
{
if(property_exists ( $Obj , $key ))
{
if(is_object($dcod->$key))
{
loadJSON($Obj->$key, json_encode($dcod->$key));
}
else
{
$Obj->$key = $dcod->$key;
}
}
}
return $Obj;
}
?>
Tested with:
<?php
class Name
{
public $first;
public $last;
public function fullname()
{
return $this->first . " " . $this->last;
}
}
$json = '{"first":"John","last":"Smith"}';
$infull = loadJSON((new Name), $json);
echo $infull->fullname();
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.13.130 (proxied: 217.100.185.202)
----
Manual Page -- https://php.net/manual/en/function.json-decode.php
Edit -- https://main.php.net/note/edit/128221
Del: integrated -- https://main.php.net/note/delete/128221/integrated
Del: useless -- https://main.php.net/note/delete/128221/useless
Del: bad code -- https://main.php.net/note/delete/128221/bad+code
Del: spam -- https://main.php.net/note/delete/128221/spam
Del: non-english -- https://main.php.net/note/delete/128221/non-english
Del: in docs -- https://main.php.net/note/delete/128221/in+docs
Del: other reasons-- https://main.php.net/note/delete/128221
Reject -- https://main.php.net/note/reject/128221
Search -- https://main.php.net/manage/user-notes.php