tablica na obiekt w php

<?php
class ArrayToObject
{
    public static function convertToObject(array $array): stdClass
    {
        $object = new stdClass();

        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $value = static::convertToObject($value);
            }

            $object->$key = $value;
        }

        return $object;
    }
}

$array = [
    'e1' => ['nume' => 'Nitu', 'prenume' => 'Andrei', 'sex' => 'm', 'varsta' => 23, 'data' => [
        'page' => 1,
        'ajax' => true,
        'title' => 'test 123'
    ]],
    'e2' => ['nume' => 'Nae', 'prenume' => 'Ionel', 'sex' => 'm', 'varsta' => 27],
    'e3' => ['nume' => 'Noman', 'prenume' => 'Alice', 'sex' => 'f', 'varsta' => 22],
    'e4' => ['nume' => 'Geangos', 'prenume' => 'Bogdan', 'sex' => 'm', 'varsta' => 23],
    'e5' => ['nume' => 'Vasile', 'prenume' => 'Mihai', 'sex' => 'm', 'varsta' => 25]
];


$obj = ArrayToObject::convertToObject($array);

echo '<pre>';
var_dump($obj->e1->data->title);
echo '</pre>';
?>
Komentarze wyłączone