Modelo

  • EN
    • English
    • Español
    • Français
    • Bahasa Indonesia
    • Italiano
    • 日本語
    • 한국어
    • Português
    • ภาษาไทย
    • Pусский
    • Tiếng Việt
    • 中文 (简体)
    • 中文 (繁體)

How to Convert stdClass Object to Array in PHP

Oct 04, 2024

Converting a stdClass object to an array in PHP is a common requirement when working with data from APIs or external sources. One way to achieve this is by using the json_decode and json_encode functions.

Here's a simple example of how to convert a stdClass object to an array:

```php

// Example stdClass object

$stdObject = new stdClass();

$stdObject->name = 'John';

$stdObject->age = 30;

// Convert stdClass object to array

$array = json_decode(json_encode($stdObject), true);

// Now $array contains the data from the stdClass object

print_r($array);

?>

```

In this example, we create a stdClass object with the properties 'name' and 'age'. We then use json_encode to convert the object to a JSON string, and then json_decode with the second parameter set to true to convert the JSON string to an associative array.

Another approach is to use the built-in get_object_vars function to convert the stdClass object to an array:

```php

// Convert stdClass object to array using get_object_vars

$array = get_object_vars($stdObject);

// Now $array contains the data from the stdClass object

print_r($array);

?>

```

The get_object_vars function returns an associative array containing all the properties of the object.

It's important to note that when working with stdClass objects, the properties can also be accessed as array elements directly, as stdClass objects implement the ArrayAccess interface. For example:

```php

// Accessing stdClass object properties as array elements

echo $stdObject->name; // Output: John

echo $stdObject->age; // Output: 30

?>

```

In conclusion, converting a stdClass object to an array in PHP can be done using json_decode and json_encode, or by using the get_object_vars function. It's important to choose the method that best fits the specific requirements of your application.

I hope this article has helped you understand how to convert stdClass objects to arrays! If you have any questions or suggestions, feel free to leave a comment below.

Recommend