Leff
Leff

Reputation: 1286

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?

Upvotes: 1

Views: 104

Answers (3)

Himanshu Upadhyay
Himanshu Upadhyay

Reputation: 6565

$contentTaxonomies = [];
foreach($contents as $content) {
    $contentTaxonomies[$content->id] = [];
    if(isset($content->taxonomies)){ // This will check if `content` has taxonomies or not. Otherwise it will give error due to for each loop
        foreach($content->taxonomies as $taxonomy){
            $contentTaxonomies[$content->id][$taxonomy->type->name] = $taxonomy->name;
        }
    }
}

Upvotes: 0

Roberto Bisello
Roberto Bisello

Reputation: 1235

simply create the array before cycle thorough taxonomies:

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

Upvotes: 0

Bartosz Herba
Bartosz Herba

Reputation: 343

You could do something like this:

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

Basicaly I initialized empty array as an value for a $content->id key and then eventually populate it with data.

Upvotes: 1

Related Questions