1

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?

1
  • don't you think that when the content will not have taxonomies then the inner foreach will give error? Commented Oct 25, 2017 at 13:45

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, of course, that is what I was looking for, thanks!
0

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;
        }
    }

Comments

0
$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;
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.