首页 \ 问答 \ 如何将两个数组合并为一个数组?(How can I combine two arrays in into one single array?)

如何将两个数组合并为一个数组?(How can I combine two arrays in into one single array?)

我不得不在我的codeigniter项目中添加更多功能。 这是jsfiddle演示 。 我有一个像这样的数组:

$faculty = array(2, 3, 4);

$message = array('test1', 'test2', 'test3');

我还有另一个数据库的最后一个插入ID:

$last_inserted_id = 1;

我想将数据组合起来形成如下数组:

$array = array(array('faculty' => 2, 'message' => 'test1', 'id' => 1),
               array('faculty' => 3, 'message' => 'test2', 'id' => 1), 
               array('faculty' => 4, 'message' => 'test3', 'id' => 1));

感谢大家的建议和时间。


I am having to add more functionality in my codeigniter project. Here is the jsfiddle demo. I have an array like this:

$faculty = array(2, 3, 4);

and

$message = array('test1', 'test2', 'test3');

I'm also having an last insert id from another database:

$last_inserted_id = 1;

I want to combine the data to form an array like this:

$array = array(array('faculty' => 2, 'message' => 'test1', 'id' => 1),
               array('faculty' => 3, 'message' => 'test2', 'id' => 1), 
               array('faculty' => 4, 'message' => 'test3', 'id' => 1));

Thanks for everyone for your suggestions and time.


原文:https://stackoverflow.com/questions/42982288
更新时间:2022-04-11 17:04

最满意答案

不,Laravel默认不会加载。 让我们一步一步来。 让我们忽略->schoolclasses; 一会儿。

App\School::with('schoolclasses')->find(2283);

这将查询数据库两次。 首先,它将使School的主键为2283.然后,它将立即查询数据库并获得所有相关的schoolclasses

App\School::find(2283);

这只会查询一次数据库。 它只会得到School 。 到目前为止还没有急切的加载。 如果您调试并跟踪数据库查询,您将看到这只会查询数据库一次,而渴望加载将查询它两次。

当你尝试通过做->schoolclasses;访问schoolclasses ->schoolclasses; ,一切都真正起作用。 那么为什么你会得到相同的结果呢? 这有点欺骗性,但不一样。 当您尝试访问schoolclasses ,Laravel将检查它是否已经急切加载。 如果是这样,它会返回schoolclasses的集合。 没有查询。 它只是立即返回它们。 但是,如果您没有急于加载它们,Laravel将在现场查询数据库并获得schoolclasses 。 最终,对于这个特定的例子,你会得到相同的结果,但是当你查询数据库时会有所不同。

然而,这实际上是热切加载的主要好处的一个不好的例子。

急切加载的主要好处是缓解N + 1查询问题。 假设你想要5所学校和所有的课程。 没有急切的加载,这是你会做的:

$schools = School::take(5)->get();

foreach ($schools as $school)
{
    $schoolclasses = $school->schoolclasses;
}

对于这样一个简单的任务,总共有6个查询。 我在下面添加了注释以了解查询来自哪里:

$schools = School::take(5)->get(); // First query

foreach ($schools as $school)
{
    // For each school, you are querying the database again to get its related classes.
    // 5 schools = 5 more queries
    $schoolclasses = $school->schoolclasses;
}

但是,如果您急于加载所有内容,则只有两个查询:

// Two queries here that fetches everything
$schools = School::with('schoolclasses')->take(5)->get();

foreach ($schools as $school)
{
    // No more queries are done to get the classes because
    // they have already been eager loaded
    $schoolclasses = $school->schoolclasses;
}

No, Laravel does not eager load by default. Lets take this step by step. Lets ignore ->schoolclasses; for a moment.

App\School::with('schoolclasses')->find(2283);

This will query the database twice. First, it will get the School with a primary key of 2283. Then, it will immediately query the database and get all the related schoolclasses.

App\School::find(2283);

This will only query the database once. It will only get the School. There is no eager loading done so far. If you debug and keep track of your database queries, you will see that this will only query the database once while eager loading will query it twice.

When you try to access the schoolclasses by doing ->schoolclasses;, everything actually works. So why do you get the same results? It is a bit deceptive, but it's not the same. When you try to access the schoolclasses, Laravel will check if it has already been eager loaded. If so, it will return the collection of schoolclasses. No querying is done. It just immediately returns them. However, if you did not eager load them, Laravel will query the database on the spot and get the schoolclasses. Ultimately, for this particular example, you get the same results, but when you query the database is different.

However, this is actually a poor example of the main benefit to eager loading.

The main benefit of eager loading is to alleviate the N + 1 query problem. Lets say you want to get 5 schools and all of its classes. Without eager loading, this is what you would do:

$schools = School::take(5)->get();

foreach ($schools as $school)
{
    $schoolclasses = $school->schoolclasses;
}

That is a total of 6 queries for such a simple task. I added comments below to understand where the queries are coming from:

$schools = School::take(5)->get(); // First query

foreach ($schools as $school)
{
    // For each school, you are querying the database again to get its related classes.
    // 5 schools = 5 more queries
    $schoolclasses = $school->schoolclasses;
}

However, if you eager load everything, you only have two queries:

// Two queries here that fetches everything
$schools = School::with('schoolclasses')->take(5)->get();

foreach ($schools as $school)
{
    // No more queries are done to get the classes because
    // they have already been eager loaded
    $schoolclasses = $school->schoolclasses;
}

相关问答

更多
  • 所以在过去的几个月里我很少想到这个问题后,我今天重新讨论了这个问题,并在laravel.io上发现了一些非常有用的代码,这些代码经历了我发现自己遇到的同样问题。 我建立在MattApril的解决方案之上,提供了一种我能想到的最简单的方法来提供一种在laravel中提供不区分大小写的关系的方法。 要实现这一点,您需要添加一些新类,这些类利用strtolower()函数创建小写密钥,允许在关系中使用的isset()函数查找不同的但是匹配的密钥: ModelCI.php (app \ Models \ Eloqu ...
  • 没有像这样的东西,但你可以使用withCount方法作为包装器来总结这种方式: $websites = Website::withCount(['valid_click_ads'=>function($query){ $query->select( DB::raw( "COALESCE(SUM(clicks),0)" ) ); }, 'facebook_ads'=>fu ...
  • 如果我正确理解你的问题,你可以使用这样的东西: Website::withCount(['valid_click_ads' => function($query) { $query->select(DB::raw('sum(revenue)')) ->where('created_at', ...); }])->get(); Using this article, I was able to put together exactly what I needed like so... ...
  • 尝试: public function allCompanies() { $companies = $this->companies()->active()->with('industry')->get(); return $companies; } with()和load()函数引用模型中的函数而不是模型本身,即: class Company extends Eloquent { public function industry() { return $ ...
  • 这是你应该使用的; 它将返回一个结果模型: $post = Post::with(array('user', 'comments.from'))->find($id); 这将返回一组结果(即使只有一个): $post = Post::with(array('user', 'comments.from'))->where('postID', $id)->get(); 而不是方法2,你可能意味着做的是: $post = Post::with(array('user', 'comments.from'))-> ...
  • 不,Laravel默认不会加载。 让我们一步一步来。 让我们忽略->schoolclasses; 一会儿。 App\School::with('schoolclasses')->find(2283); 这将查询数据库两次。 首先,它将使School的主键为2283.然后,它将立即查询数据库并获得所有相关的schoolclasses 。 App\School::find(2283); 这只会查询一次数据库。 它只会得到School 。 到目前为止还没有急切的加载。 如果您调试并跟踪数据库查询,您将看到这只 ...
  • 使用whereHas方法: Recipient::with('location') ->where('company_id', auth()->user()->company_id) ->whereHas('teams', function($q){ return $q->where('id', 10); }) ->get(); Use the whereHas method for this: Recipient::with('location') ...
  • 您应该在模型中定义方法。 据我所知,你将有一对多的关系。 而那将是 class Question extends Model { public function tags() { return $this->hasMany('App\Tag'); } } 标签类 class Tag extends Model { public function question() { return $this->belongsTo('App\Que ...
  • 延迟加载的潜在好处(即 - 不是急切加载)与预期加载(即性能)相同。 在您可能不需要和/或不访问相关模型的情况下,延迟加载可以提高应用程序的整体速度。 同样,当您更有可能需要相关模型时,急切加载将是正确的选择。 根据我的经验,考虑到额外查询的开销,我会在您不太可能需要其他模型的情况下保存延迟加载。 The potential benefit of lazy loading, (i.e. - not eager loading), is the same as eager loading, namely pe ...
  • 您应该可以通过在getPaginated函数中包含eager-load来实现: public function getPaginated(array $params) { $list = Lists::newQuery(); // See if there are any search results that need to be accounted for if ($params['search'] != null) $list->where('name', 'LIKE' ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)