Home > Enterprise >  Adding param with value to array
Adding param with value to array

Time:07-09

I have this code:

    $campaignUserModel = new CampaignUserModel();
    $subcontractors = $campaignUserModel
        ->select('campaigns_users.*, users.fullname user_fullname')
        ->join('users', 'users.id = campaigns_users.user_id')
        ->where('campaign_id', $id)
        ->findAll();

    $postModel = new PostModel();
    foreach ($subcontractors as $subcontractor) {
        $subcontractor_posts = $postModel
            ->where('user_id', $subcontractor['id'])
            ->where('campaign_id', $id)
            ->countAllResults();

        $subcontractor['posts_count'] = $subcontractor_posts;

        echo "<pre>";
        var_dump($subcontractor);
        echo "</pre>";
    }

    echo "<pre>";
    var_dump($subcontractors);
    echo "</pre>";

In first var_dump() I see:

array(7) { ["id"]=> string(1) "3" ["campaign_id"]=> string(1) "1" ["user_id"]=> string(1) "3" ["quantity"]=> string(1) "2"
["status"]=> string(1) "2" ["user_fullname"]=> string(17) "Edek Podwykonawca" ["posts_count"]=> int(1) }

so posts_count is added. But when foreach finished and I display second var_dump() with array of all subcontractor i can't see posts_count.

Where am I making a mistake?

CodePudding user response:

You need to pass the $subcontractor variable by reference:

I.e:

Instead of:❌

// ...
 foreach ($subcontractors as $subcontractor) {
// ...

Use this:✅

// ...
 foreach ($subcontractors as &$subcontractor) {
// ...

Notice the ampersand (&) infront of $subcontractor

Resource: References Explained

  • Related