Modelo

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

Converting stdClass object to array in PHP

Oct 12, 2024

When working with PHP, you may come across situations where you need to convert a stdClass object to an array. This can be useful when dealing with data fetched from APIs or databases. One way to achieve this is by using the json_decode and json_encode functions.

To convert a stdClass object to an array, you can first use the json_encode function to convert the object to a JSON string. Then, you can use the json_decode function with the second parameter set to true to convert the JSON string back to an associative array.

Here's an example of how you can achieve this:

$stdClassObject = new stdClass();

$stdClassObject->name = 'John Doe';

$stdClassObject->age = 30;

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

In this example, we first create a stdClass object with the properties name and age. Then, we use json_encode to convert the object to a JSON string, and json_decode with the second parameter set to true to convert the JSON string to an array. The resulting $array variable will now contain the data from the original stdClass object in array format.

Keep in mind that this method may not work as expected if your stdClass object contains nested objects or arrays. In such cases, you may need to use a recursive function to convert all nested objects and arrays to arrays as well.

In conclusion, converting a stdClass object to an array in PHP can be achieved using the json_decode and json_encode functions. It's a simple and effective way to work with data in array format. Just remember to handle nested objects and arrays appropriately if needed.

Recommend