Leff7's avatar
Level 4

PHP - pushing only key first to an array and adding values later

I have a foreach loop where I go through a collection of contents and I am making an associative array with values from a relationship of contents. This is the code:

    $contentTaxonomies = [];
    foreach($contents as $content) {
        foreach($content->taxonomies as $taxonomy){
            $contentTaxonomies[$content->id][$taxonomy->type->name] = $taxonomy->name;
        }
    }

But, that means if the content doesn't have any taxonomies it won't be in the $contentTaxonomies array, how can I make a loop that when it doesn't have taxonomies, it still gets add to an array just with empty value?

0 likes
2 replies
36864's avatar
36864
Best Answer
Level 13
$contentTaxonomies = [];
foreach($contents as $content) {
    $contentTaxonomies[$content->id] = [];
    foreach($content->taxonomies as $taxonomy){
        $contentTaxonomies[$content->id][$taxonomy->type->name] = $taxonomy->name;
    }
}
        
1 like
ftrillo's avatar

That looks like a nested array more than an associative array.

If you want an array of contents where the key is the content_id and the value is an array of taxonomy names, try this:

(assuming you defined a taxonomies relation method in the content model)

$contentTaxonomies = [];
foreach($contents as $content) {
    $contentTaxonomies[$content->id] = $content->taxonomies->pluck('name');
}

or

$contentTaxonomies = $contents->keyBy('id')->transform(function($content) {
    return $content->taxonomies->pluck('name');
})->all();

Please or to participate in this conversation.