Home » Php » mysql – How to create and access complex object in php

mysql – How to create and access complex object in php

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have 2 mysql tables that look like:

users:         usr   fname   lname   email   news   wres   SWAGLeaders
campaigns:     usr   subject   value

the tables are linked through usr. For each usr campaigns contains 4 distinct subjects (cleanup,gas,cca and pollinators).

I do basic queries to the database:

$users = query("select * from users");
$camps = query("select distinct usr from campaigns");

every usr in $camp will also be in $users but every usr in $users may not be in $camp. Both $camp and $users are sorted in ascending usr order.

I want to build a completely independent object that has the following form:

{
    [email protected]:[
        usr:130, 
        fname:'bob', 
        lname:'henry', 
        news:1, 
        wres:1, 
        SWAGLeader:1, 
        cleanup:1, 
        gas:0, 
        cca:0, 
        pollinators:1
} 

I start off as follows:

$icnt = count($users);
$ccnt = count($camp);
$all = [];
for($int i = 0;$i<$cnt;$i++){
     $obj = new stdClass();
     $obj->{$user[i]['email']}=['usr'=>$user[0]['usr']];
     $iusr = $user[i]['usr'];

    // so at this point I have the the start of my first obj
    // how do I add in usr,fname,lanme,news,wres and SWAGLeaders into the array?

     for($k= 0;$k <6;$k++){
         ???????
     }

     for($j=0;$j<$ccnt;$j++){
        $cusr = $camp[$j]['usr'];
        if($cusr === $iusr){
            $usrCamp = query("select * from camp where usr = ?",$cusr);

            //so now I need to add in the 4 campaigns with values from $usrCamp
           for($k=0;$k<4;$k++){
                ????
           }
        }else{
            // and here I need to add in the 4 campaigns with no data (nulls)
            for($k=0;$k<4;$k++){
                ????
            }
        }
    }

      array_push($obj,$all);
}

Finally in a nested loop, how do I access each element in $all, basically for each email address how do I access the elements in the array? How do I assign them to other variables by value (not reference)

How to&Answers: