ご覧いただきありがとうございます!
PHP初心者のため、「何言ってんだこいつ」と思われるかもしれませんが、ご容赦ください。
PHP
1//TestController 2 public function friends(Request $request) 3 { 4 5 //foreachでfriend_idをidにもつuserを取得してこの配列に入れたい 6 $friends = []; 7 8 //hasManyでfriend_idを配列で取得 9 /*[ 10 { 11 "friend_id": 1 12 }, 13 { 14 "friend_id": 4 15 }, 16 { 17 "friend_id": 2 18 } 19 ]*/ 20 $friend_ids = $this->user::find($request['id'])->friends; 21 22 foreach ($friend_ids as $key => $value) { 23 $friends[] = $this->user::find($value); 24 } 25 26 $data = [ 27 'friends' => $friends, 28 ]; 29 30 return response()->json($data); 31 }
json
1//このレスポンスが返ってきてしまう 2"friends": [ 3 [ 4 { 5 "id": 1, 6 "email": "kishimoto@gmail.co.jp", 7 "password": "kishimoto", 8 "name": "岸本", 9 "tenant_id": 2, 10 "friend_code": 543673, 11 "role": 0, 12 "valid": 0, 13 "comment": null, 14 "created_at": "-0001-11-30 00:00:00", 15 "updated_at": "-0001-11-30 00:00:00" 16 } 17 ], 18 [ 19 { 20 "id": 4, 21 "email": "hashimoto@gmail.co.jp", 22 "password": "hashimoto", 23 "name": "橋下", 24 "tenant_id": 2, 25 "friend_code": 284763, 26 "role": 0, 27 "valid": 0, 28 "comment": null, 29 "created_at": "-0001-11-30 00:00:00", 30 "updated_at": "-0001-11-30 00:00:00" 31 } 32 ], 33 [ 34 { 35 "id": 2, 36 "email": "tanaka@gmail.co.jp", 37 "password": "tanaka", 38 "name": "田中", 39 "tenant_id": 4, 40 "friend_code": 857034, 41 "role": 0, 42 "valid": 0, 43 "comment": null, 44 "created_at": "-0001-11-30 00:00:00", 45 "updated_at": "-0001-11-30 00:00:00" 46 } 47 ] 48 ]
JSON
1//本当はこうしたい 2{ 3 "friends": [ 4 { 5 "id": 2, 6 "email": "tanaka@gmail.co.jp", 7 "password": "tanaka", 8 "name": "田中", 9 "tenant_id": 4, 10 "friend_code": 857034, 11 "role": 0, 12 "valid": 0, 13 "comment": null, 14 "created_at": "-0001-11-30 00:00:00", 15 "updated_at": "-0001-11-30 00:00:00" 16 }, 17 { 18 "id": 4, 19 "email": "hashimoto@gmail.co.jp", 20 "password": "hashimoto", 21 "name": "橋下", 22 "tenant_id": 2, 23 "friend_code": 284763, 24 "role": 0, 25 "valid": 0, 26 "comment": null, 27 "created_at": "-0001-11-30 00:00:00", 28 "updated_at": "-0001-11-30 00:00:00" 29 }, 30 { 31 "id": 1, 32 "email": "kishimoto@gmail.co.jp", 33 "password": "kishimoto", 34 "name": "岸本", 35 "tenant_id": 2, 36 "friend_code": 543673, 37 "role": 0, 38 "valid": 0, 39 "comment": null, 40 "created_at": "-0001-11-30 00:00:00", 41 "updated_at": "-0001-11-30 00:00:00" 42 } 43 ] 44}
返したいJSONが[]に入ってしまい、アプリ側で取り出しづらいです。
返したいレスポンスは
$friends[0] = $this->user::find($friend_ids[0]['friend_id']);
$friends[1] = $this->user::find($friend_ids[1]['friend_id']);
で作れるのですが、foreachで回すと[]の中に入ってしまいます。
{}と[]の違いもいまいち理解できてないのですが、
foreachと$friends[0]とやっている処理は同じではないのでしょうか?
PHP
1//Userクラスになります 2class User extends Model 3{ 4 5 public function friends() 6 { 7 8 $friend_ids = $this -> hasMany('App\Friend')->select(['friend_id']); 9 return $friend_ids; 10 11 } 12}
回答5件
あなたの回答
tips
プレビュー