表user有两个字段,id,name
表user_friend有三个字段,id,userid,friendid
$query = $this->db->query('SELECT * FROM user where id=46' );
$user=$query->row();
$queryfriend= $this->db->query('SELECT * FROM user_friend where userid='.$user->id );
$userfriend=$queryfriend->result();
各位亲,请问下我要输出如下的json格式,应该怎样操作?
{
"user": {
"id": "46",
"name": "john",
"userfriend": [ {
"id": "13",
"userId": "46",
"friendId": "43"
},
{
"id": "15",
"userId": "46",
"friendId": "44"
}
]
}
}
回复讨论(解决方案)
print_r($userfriend);
看看都是什么
print_r($userfriend)结果如下;
Array ( [0] => stdClass Object ( [id] => 13 [userId] => 46 [friendId] => 43 ) [1] => stdClass Object ( [id] => 15 [userId] => 46 [friendId] => 44 ) [2] => stdClass Object ( [id] => 16 [userId] => 46 [friendId] => 45 ) )
userfriend输出数据库查出来对应的[]格式就行了
这样试试
$user['userfriend']=$userfriend;
$data['user']=$user;
echo json_encode($data);
$user['userfriend']=$userfriend;
$data['user']=$user;
echo json_encode($data);
输出如下,不是我想要的格式
{
"user": {
"0": {
"id": "45",
"nickName": "Jerry",
"gender": "1",
"birthday": "2000年10月01日",
"avatar": "upload/user/45/avatar/0434541421051694278.jpg",
},
"userfriend": [
{
"id": "5",
"userId": "45",
"friendId": "3",
"endTime": "1426745161"
},
{
"id": "7",
"userId": "45",
"friendId": "5",
"endTime": "1426745161"
},
{
"id": "9",
"userId": "45",
"friendId": "44",
"endTime": "1426745161"
},
{
"id": "10",
"userId": "45",
"friendId": "46",
"endTime": "1426745161"
}
]
}
}
我的想法:
1.拼接json
1).循环$user,嵌套循环$userfriend
2.重组数组
1).两表联查
2).循环构造新数组
额外:
json_encode()注意编码UTF-8
这样就可以了。
$query = $this->db->query('SELECT * FROM user where id=46' );$user=$query->row();$queryfriend= $this->db->query('SELECT * FROM user_friend where userid='.$user->id );$userfriend=$queryfriend->result();$data = array();$data['user']['id'] = $user[0]['id'];$data['user']['name'] = $user[0]['name'];$data['user']['userfriend'] = $userfriend;echo json_encode($data);
先取出所有用户,foreach循环取出每个用户的朋友,在保存到一个数值里面
正确的代码如下,感谢各位
$user = $query->result_array();
$data = $user[0];
$data['userfriend'] = $userfriend;
// $result = array('result' => array('status' => '1', 'message' => '登陆成功', 'user' => $data));
$result = array( 'user' => $data);
echo json_encode($result);

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use
