简体   繁体   English

如何将数组中的值附加到另一个数组中的另一个键

[英]How to attach values from an array to another key in another array

I'm using laravel query-builder to get data from database but what I need is just based on php.我正在使用 laravel 查询生成器从数据库中获取数据,但我需要的只是基于 php。

Here's some code:这是一些代码:

$data = DB::select('SELECT * FROM news ORDER BY created_at DESC'):
foreach ($data as $rows) {
    $teacher = DB::select('SELECT name FROM teachers WHERE id = ?', [$row->teacher_id]);
    $data->teacher = $teacher; 
}
return $data;

The $data variable has the following array: $data 变量具有以下数组:

array:4[
    0 => {
        "id":3
        "teacher_id": 2
    }
    1 => {...some similar keyvalue pairs}
    2 => { ...another key-value pairs}
]

So the question is that I want the teacher name from the database to be attached to each $data array iteration by using the id from each $data iteration to get the teacher name from the second query.所以问题是我希望数据库中的教师姓名附加到每个$data数组迭代中,方法是使用每个$data迭代中的id从第二个查询中获取教师姓名。

Does anyone get this?有人得到这个吗?

You can solve this issu using a single query..您可以使用单个查询来解决此问题。

SELECT news.*, teachers.name 
FROM news
INNER JOIN  teachers where teachers.id = news.teacher_id
ORDER BY created_at DESC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM