Skip to content

Instantly share code, notes, and snippets.

@jlambe
Created March 24, 2022 08:25
Show Gist options
  • Save jlambe/da062e717c391d423a139186e410fc02 to your computer and use it in GitHub Desktop.
Save jlambe/da062e717c391d423a139186e410fc02 to your computer and use it in GitHub Desktop.
Flatten data objects
<?php
class PostContentData {
public function __construct(
public string $excerpt,
public string $content,
) {}
}
class SettingsData {
public function __construct(
public string $name,
public string $title,
public PostContentData $post,
)
{}
}
/*
* Given the following objects, calling the `toArray()` method will produce this array:
*/
[
'name' => 'John',
'title' => 'The Hero',
'post' => [
'excerpt' => 'Story summary',
'content' => 'A long time ago...'
],
]
/*
* I would have liked a native method to flatten the transformed data where for each nested data objects,
* we only get their properties like so, putting them all at the same level:
*/
[
'name' => 'John',
'title' => 'The Hero',
'excerpt' => 'Story summary',
'content' => 'A long time ago...'
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment