Oihana PHP

toAssociativeArray.php

Table of Contents

Functions

toAssociativeArray()  : array<string|int, mixed>
Recursively converts an object (or array) into a full associative array.

Functions

toAssociativeArray()

Recursively converts an object (or array) into a full associative array.

toAssociativeArray(array<string|int, mixed>|object $document[, string|array<string|int, mixed>|object|null $encoder = null ][, bool $strict = false ]) : array<string|int, mixed>

This function handles nested objects, ensuring the entire array or object tree is converted.

Note that only public properties of the object will be included in the resulting array.

Parameters
$document : array<string|int, mixed>|object

An array or object to convert to a deep associative array .

$encoder : string|array<string|int, mixed>|object|null = null

Optional JSON encoder reference. This value is resolved into a callable using resolveCallable(). Supported forms:

  • Closure or invokable object
  • Callable array: [$object, 'method'] or ['Class', 'method']
  • Named function: 'my_json_encoder'
  • Static method string: 'MyClass::encode'
  • null to use native json_encode()

The resolved callable must have the signature: function(mixed $data): string

$strict : bool = false

If strict, not use json_encode but a standard loop.

Tags
example

Convert an object :

// Define some classes for the example.
class Address
{
    public string $street = '123 PHP Avenue';
    public string $city = 'Codeville';
}

class User
{
    public int $id = 42;
    public string $name = 'John Doe';
    public Address $address;
    private string $sessionToken = 'a-very-secret-token'; // This will be ignored.

    public function __construct()
    {
        $this->address = new Address();
    }
}

$userObject = new User();

$userArray = toAssociativeArray($userObject);

print_r($userArray);
// Output:
// Array
// (
//     [id] => 42
//     [name] => John Doe
//     [address] => Array
//      (
//          [street] => 123 PHP Avenue
//          [city] => Codeville
//      )
// )
// Note that the private property 'sessionToken' is not present.

Convert an array with sub-objects:

$data = (object)
[
    'id' => 123,
    'name' => 'Project Alpha',
    'provider' => (object)
    [
       'name' => 'Alice',
       'role' => 'Chef de projet'
    ],
    'team' =>
     [
        (object) ['name' => 'Bob'     ] ,
        (object) ['name' => 'Charlie' ]
     ]
];

$arrayAssoc = toAssociativeArray($data);

print_r($arrayAssoc);

Convert using a custom JSON encoder (Closure):

$encoder = function (mixed $data): string
{
    // Example: pretty-print JSON and remove null values
    return json_encode($data, JSON_PRETTY_PRINT);
};

$result = toAssociativeArray($userObject, $encoder);

print_r($result);

Convert using a static serializer method:

use oihana\reflect\utils\JsonSerializer;
use oihana\core\options\ArrayOption;

$result = toAssociativeArray
(
$userObject,
   fn(mixed $data): string =>
       JsonSerializer::encode( $data , jsonFlags: 0 , options: [ArrayOption::REDUCE => true] )
);

print_r($result);

Convert using a named function or static method string:

// Using a named function
function my_json_encoder(mixed $data): string
{
    return json_encode($data, JSON_UNESCAPED_SLASHES);
}

$result1 = toAssociativeArray($userObject, 'my_json_encoder');

// Using a static method string
$result2 = toAssociativeArray($userObject, 'MyJsonHelper::encode');

print_r($result1);
print_r($result2);
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
array<string|int, mixed>

The resulting associative array.


        
On this page

Search results