Created
June 29, 2016 07:39
-
-
Save assertchris/d09111f43e183fe6d9397d47d87dafdd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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