Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@assertchris
Created June 29, 2016 07:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save assertchris/d09111f43e183fe6d9397d47d87dafdd to your computer and use it in GitHub Desktop.
Save assertchris/d09111f43e183fe6d9397d47d87dafdd to your computer and use it in GitHub Desktop.
<?php
function marshal(array $rows) {
foreach ($rows as $row) {
assert(is_object($row));
assert(property_exists($row, "id"));
assert(property_exists($row, "type"));
$row->relatives = array_filter($rows, function ($next) use ($row) {
$key = "{$row->type}_id";
if (property_exists($next, $key)) {
return $next->$key === $row->id;
}
});
yield $row;
}
}
$rows = json_decode(json_encode([
["type" => "blog", "id" => 1, "taxonomy_id" => 1],
["type" => "blog", "id" => 2, "taxonomy_id" => 2],
["type" => "post", "id" => 1, "blog_id" => 1, "taxonomy_id" => 1],
["type" => "post", "id" => 2, "blog_id" => 1, "taxonomy_id" => 2],
["type" => "post", "id" => 3, "blog_id" => 2, "taxonomy_id" => 1],
["type" => "post", "id" => 4, "blog_id" => 2, "taxonomy_id" => 2],
["type" => "taxonomy", "id" => 1],
["type" => "taxonomy", "id" => 2],
]));
print_r(
iterator_to_array(
marshal($rows)
)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment