首页 > 解决方案 > 如何在 php 中创建和访问复杂对象

问题描述

我有 2 个 mysql 表,如下所示:

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

这些表通过 usr 链接。对于每个 usr 活动,都包含 4 个不同的主题(cleanup、gas、cca 和 pollinators)。

我对数据库进行基本查询:

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

$camp 中的每个 usr 也将在 $users 中,但 $users 中的每个 usr 可能不在 $camp 中。$camp 和 $users 都按 usr 升序排序。

我想构建一个具有以下形式的完全独立的对象:

{
    abc@gmail.com:[
        usr:130, 
        fname:'bob', 
        lname:'henry', 
        news:1, 
        wres:1, 
        SWAGLeader:1, 
        cleanup:1, 
        gas:0, 
        cca:0, 
        pollinators:1
} 

我开始如下:

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

最后在一个嵌套循环中,我如何访问 $all 中的每个元素,基本上对于每个电子邮件地址,我如何访问数组中的元素?如何按值将它们分配给其他变量(不是参考)

标签: phpmysqlobjectcopykey

解决方案


推荐阅读