note 124321 added to language.types.array
| From: | Anonymous@php.net | Date: | Tue, 22 Oct 2019 16:29:48 +0000 |
| Subject: | note 124321 added to language.types.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-212747@lists.php.net to get a copy of this message | ||
Wrappers for (array), returns array with normalize keys (without prefix):
<?php
function to_array_recursive($value): array
{
if (! is_object($value)) {
return (array) $value;
}
$class = get_class($value);
$arr = [];
foreact ((array) $value as $key => $val) {
$key = str_replace(["\0*\0", "\0{$class}\0"], '',
$key);
$arr[$key] = is_object($val) ? to_array_recursive($val) : $val;
}
return $arr;
}
function to_array($value): array
{
$arr = (array) $value;
if (! is_object($value)) {
return $arr;
}
$class = get_class($value);
$keys = str_replace(["\0*\0", "\0{$class}\0"], '',
array_keys($arr));
return array_combine($keys, $arr);
}
?>
Demo:
<?php
class Test
{
protected $var = 1;
protected $var2;
private $TestVar = 3;
public function __construct($isParent = true)
{
if ($isParent) {
$this->var2 = new self(! $isParent);
}
}
}
$obj = new Test();
var_dump((array) $obj, to_array_recursive($obj));
?>
----
Server IP: 208.43.231.9
Probable Submitter: 185.85.3.168 (proxied: 31.129.195.213)
----
Manual Page -- http://php.net/manual/en/language.types.array.php
Edit -- https://master.php.net/note/edit/124321
Del: integrated -- https://master.php.net/note/delete/124321/integrated
Del: useless -- https://master.php.net/note/delete/124321/useless
Del: bad code -- https://master.php.net/note/delete/124321/bad+code
Del: spam -- https://master.php.net/note/delete/124321/spam
Del: non-english -- https://master.php.net/note/delete/124321/non-english
Del: in docs -- https://master.php.net/note/delete/124321/in+docs
Del: other reasons-- https://master.php.net/note/delete/124321
Reject -- https://master.php.net/note/reject/124321
Search -- https://master.php.net/manage/user-notes.php