当子数组在 php 中具有相同的键时,查询多维数组的值的最有效方法
首先,我从数据库查询中获得了一个结果数组,我通过 foreach 将其吐出到 html 列表中。其次,我有一个包含相关数据的多维数组。该关系在两个数据源中均由“entry_id”定义。
我想在 foreach 的每次迭代中查询多维数组,以检查是否有匹配的entry_id,如果有,我想将页面标题拉出以添加到我的html列表中。 多维数组如下所示:
array(4) {
[0]=> array(2) {
["entry_id"]=> string(1) "1"
["title"]=> string(4) "Page Title 1"
}
[1]=> array(2) {
["entry_id"]=> string(1) "2"
["title"]=> string(5) "Page Title 2"
}
[2]=> array(2) {
["entry_id"]=> string(1) "3"
["title"]=> string(8) "Page Title 3"
}
[3]=> array(2) {
["entry_id"]=> string(1) "4"
["title"]=> string(5) "Page Title 4" }
}
那么首先,您将如何查询该多维数组并获取该迭代中所需的页面标题,同时记住子数组具有相同的键?
其次,最有效的方法是什么,我还应该提到,理论上数组可能会变得非常大。
First of all, I've got a result array from a db query that i'm spitting out into a html list via a foreach. Secondly I have got a multi-dimensional array with related data in. The relationship is defined in both data sources by "entry_id".
I want to query the multi-dimensional array on each iteration of the foreach to check if there is a matching entry_id, and if so i want to pull the page title out to add into my html list.
The multi-dimensional array looks like this:
array(4) {
[0]=> array(2) {
["entry_id"]=> string(1) "1"
["title"]=> string(4) "Page Title 1"
}
[1]=> array(2) {
["entry_id"]=> string(1) "2"
["title"]=> string(5) "Page Title 2"
}
[2]=> array(2) {
["entry_id"]=> string(1) "3"
["title"]=> string(8) "Page Title 3"
}
[3]=> array(2) {
["entry_id"]=> string(1) "4"
["title"]=> string(5) "Page Title 4" }
}
So firstly, how would you query that multi-dimensional array and get the page title out that you need on that iteration, bearing in mind the sub-arrays have identical keys?
Secondly, what is the most efficient method of doing this, I should also mention that the array could get very large in theory.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
转换数组,以便获得结构
,
即获取标题只需使用
entry_id
的值访问数组即可。如果可以的话,从头开始构建这样的数组,如果不能,则必须迭代它并创建这个结构。
Transform the array so that you have the structure
i.e.
Then getting the title is just accessing the array with the value of the
entry_id
.If you can, build the array like this from the beginning, if not, you have to iterate over it and create this structure.