Jak przekonwertować tablicę na obiekt przy użyciu stdClass()

Zrobiłem następującą tablicę:

$clasa = array(
        'e1' => array('nume' => 'Nitu', 'prenume' => 'Andrei', 'sex' => 'm', 'varsta' => 23),
        'e2' => array('nume' => 'Nae', 'prenume' => 'Ionel', 'sex' => 'm', 'varsta' => 27),
        'e3' => array('nume' => 'Noman', 'prenume' => 'Alice', 'sex' => 'f', 'varsta' => 22),
        'e4' => array('nume' => 'Geangos', 'prenume' => 'Bogdan', 'sex' => 'm', 'varsta' => 23),
        'e5' => array('nume' => 'Vasile', 'prenume' => 'Mihai', 'sex' => 'm', 'varsta' => 25)
);

Chciałbym wiedzieć, jak przekonwertować tablicę na obiekt za pomocą stdClass (), Jestem początkującym PHP, prosty przykład byłby bardzo pomocny, próbowałem szukać podobnych pytań, ale odpowiedzi są skomplikowane i wykraczają poza moje zrozumienie podstawowych klas i obiektów.

Author: Charles, 2013-10-09

8 answers

Wystarczy dodać ten kod

$clasa = (object) array(
            'e1' => array('nume' => 'Nitu', 'prenume' => 'Andrei', 'sex' => 'm', 'varsta' => 23),
            'e2' => array('nume' => 'Nae', 'prenume' => 'Ionel', 'sex' => 'm', 'varsta' => 27),
            'e3' => array('nume' => 'Noman', 'prenume' => 'Alice', 'sex' => 'f', 'varsta' => 22),
            'e4' => array('nume' => 'Geangos', 'prenume' => 'Bogdan', 'sex' => 'm', 'varsta' => 23),
            'e5' => array('nume' => 'Vasile', 'prenume' => 'Mihai', 'sex' => 'm', 'varsta' => 25)
);

Jeśli chcesz zobaczyć, czy jest to obiekt stdClass, wywołaj to

print_r($clasa);

Jeśli chcesz przekonwertować tablicę na kod obiektowy będzie

$arr = array('a'=>'apple','b'=>'ball');
$arr = (object) $arr;
Nie musisz używać stdClass. Zostanie automatycznie przekonwertowany na stdClass
 172
Author: Ekramul Hoque,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-06 11:55:58

Szybki i brudny sposób jest za pomocą json_encode oraz json_decode który zamieni całą tablicę (w tym podelementy) w obiekt.

$clasa = json_decode(json_encode($clasa)); //Turn it into an object

To samo może być użyte do konwersji obiektu na tablicę. Po prostu dodaj , true do json_decode, aby zwrócić skojarzoną tablicę:

$clasa = json_decode(json_encode($clasa), true); //Turn it into an array

Alternatywną drogą (bez bycia brudnym) jest po prostu funkcja rekurencyjna:

function convertToObject($array) {
    $object = new stdClass();
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $value = convertToObject($value);
        }
        $object->$key = $value;
    }
    return $object;
}

Lub w pełnym kodzie:

<?php
    function convertToObject($array) {
        $object = new stdClass();
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $value = convertToObject($value);
            }
            $object->$key = $value;
        }
        return $object;
    }

    $clasa = array(
            'e1' => array('nume' => 'Nitu', 'prenume' => 'Andrei', 'sex' => 'm', 'varsta' => 23),
            'e2' => array('nume' => 'Nae', 'prenume' => 'Ionel', 'sex' => 'm', 'varsta' => 27),
            'e3' => array('nume' => 'Noman', 'prenume' => 'Alice', 'sex' => 'f', 'varsta' => 22),
            'e4' => array('nume' => 'Geangos', 'prenume' => 'Bogdan', 'sex' => 'm', 'varsta' => 23),
            'e5' => array('nume' => 'Vasile', 'prenume' => 'Mihai', 'sex' => 'm', 'varsta' => 25)
    );

    $obj = convertToObject($clasa);
    print_r($obj);
?>

Które wyjścia (zauważ, że nie ma tablic - tylko stdClass's):

stdClass Object
(
    [e1] => stdClass Object
        (
            [nume] => Nitu
            [prenume] => Andrei
            [sex] => m
            [varsta] => 23
        )

    [e2] => stdClass Object
        (
            [nume] => Nae
            [prenume] => Ionel
            [sex] => m
            [varsta] => 27
        )

    [e3] => stdClass Object
        (
            [nume] => Noman
            [prenume] => Alice
            [sex] => f
            [varsta] => 22
        )

    [e4] => stdClass Object
        (
            [nume] => Geangos
            [prenume] => Bogdan
            [sex] => m
            [varsta] => 23
        )

    [e5] => stdClass Object
        (
            [nume] => Vasile
            [prenume] => Mihai
            [sex] => m
            [varsta] => 25
        )

)

Więc odnosisz się do niego przez $obj->e5->nume.

DEMO

 43
Author: h2ooooooo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-09 12:38:14

Jeśli chcesz rekurencyjnie przekonwertować całą tablicę na typ obiektu (stdClass), poniżej znajduje się najlepsza metoda i nie jest czasochłonna ani nie ma niedoboru pamięci, szczególnie gdy chcesz wykonać rekurencyjną (wielopoziomową) konwersję w porównaniu do pisania własnej funkcji.

$array_object = json_decode(json_encode($array));
 12
Author: darleys,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-28 07:16:29

Jednym z najprostszych rozwiązań jest

$objectData = (object) $arrayData
 6
Author: SESN,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-28 07:16:21

Aby przekonwertować tablicę na obiekt używając stdClass wystarczy dodać (object) do tablicy u declare.

EX:

echo $array['value'];
echo $object->value;

Aby przekonwertować obiekt do tablicy

$obj = (object)$array;

Do konwersji tablicy na obiekt

$arr = (array)$object

Za pomocą tych metod można bardzo łatwo zamienić tablicę i obiekt.


Inną metodą jest użycie json

$object = json_decode(json_encode($array), FALSE);

Ale jest to znacznie bardziej intensywny sposób na pamięć i nie jest obsługiwany przez wersje PHP

 5
Author: Vikas_web,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-12 11:23:20

Array to stdClass można wykonać w php w ten sposób. (stdClass jest już standardową pustą klasą PHP)

$a = stdClass:: __set_state(array());

Wywołanie stdClass:: _ _ set _ state () w PHP 5 spowoduje błąd krytyczny. dzięki @ Ozzy za wskazanie

To jest przykład jak można użyć _ _ set _ state () z obiektem stdClass w PHP5

class stdClassHelper{

    public static function __set_state(array $array){
        $stdClass = new stdClass();
        foreach ($array as $key => $value){
           $stdClass->$key = $value;
        }
        return $stdClass;
    }
}

$newstd = stdClassHelper::__set_state(array());
Albo w milszy sposób.
$a = (object) array();
 4
Author: Beaudinn Greve,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-17 13:09:41

Or you can use this thing

$arr = [1,2,3];
$obj = json_decode(json_encode($arr));
print_r($obj);
 3
Author: yussan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-04 05:42:07

Użyj tego tutoriala

<?php
function objectToArray($d) {
        if (is_object($d)) {
            // Gets the properties of the given object
            // with get_object_vars function
            $d = get_object_vars($d);
        }

        if (is_array($d)) {
            /*
            * Return array converted to object
            * Using __FUNCTION__ (Magic constant)
            * for recursive call
            */
            return array_map(__FUNCTION__, $d);
        }
        else {
            // Return array
            return $d;
        }
    }

    function arrayToObject($d) {
        if (is_array($d)) {
            /*
            * Return array converted to object
            * Using __FUNCTION__ (Magic constant)
            * for recursive call
            */
            return (object) array_map(__FUNCTION__, $d);
        }
        else {
            // Return object
            return $d;
        }
    }

        // Create new stdClass Object
    $init = new stdClass;

    // Add some test data
    $init->foo = "Test data";
    $init->bar = new stdClass;
    $init->bar->baaz = "Testing";
    $init->bar->fooz = new stdClass;
    $init->bar->fooz->baz = "Testing again";
    $init->foox = "Just test";

    // Convert array to object and then object back to array
    $array = objectToArray($init);
    $object = arrayToObject($array);

    // Print objects and array
    print_r($init);
    echo "\n";
    print_r($array);
    echo "\n";
    print_r($object);


//OUTPUT
    stdClass Object
(
    [foo] => Test data
    [bar] => stdClass Object
        (
            [baaz] => Testing
            [fooz] => stdClass Object
                (
                    [baz] => Testing again
                )

        )

    [foox] => Just test
)

Array
(
    [foo] => Test data
    [bar] => Array
        (
            [baaz] => Testing
            [fooz] => Array
                (
                    [baz] => Testing again
                )

        )

    [foox] => Just test
)

stdClass Object
(
    [foo] => Test data
    [bar] => stdClass Object
        (
            [baaz] => Testing
            [fooz] => stdClass Object
                (
                    [baz] => Testing again
                )

        )

    [foox] => Just test
)
 1
Author: Shakti Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-09 12:37:27