php - 如何在 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 中的每个元素,基本上对于每个电子邮件地址,我如何访问数组中的元素?如何按值将它们分配给其他变量(不是参考)
解决方案
推荐阅读
- javascript - 类组件中的 ReactJs 嵌套路由切换
- python - 从数据框中的每个组中删除特定的一组行
- javascript - 如何定期更改状态值?
- git - 如何将代码提交到 Github 上的子文件夹
- oracle - 生成字母数字字段和增量
- javascript - 通过 superagent 在本地项目上响应 Ajax 请求
- javascript - 如何使用 DialogFlow 的方法 projects.agent.import 将 zip 文件导入代理?
- javascript - 通过单选按钮更改样式表
- linkedin - LinkedIn oAuth2 底层连接已关闭:发送时发生意外错误
- asp.net - IIS 10 Web 路由配置