gpt4 book ai didi

php - 通过多个索引引用 PHP 数组

转载 作者:可可西里 更新时间:2023-11-01 13:11:39 26 4
gpt4 key购买 nike

这可能是某种奇怪的更长的捷径,如果我在这个思路上有误,请纠正我......

我有一个数据矩阵,如下所示:

unique_id | url | other random data...
unique_id | url | other random data...
unique_id | url | other random data...

我希望能够通过 url 或 unique_id 来引用一个项目 - 有没有一种奇特的方法可以做到这一点?

我想作弊的解决方案是只制作两个数组,但我想知道是否有更好的方法。

最佳答案

我能想到的唯一不涉及为每次搜索迭代数组的方法(请参阅 Jacob 的回答)是将对每个项目的引用存储在两个数组中。

编辑:由于 URL 和 ID 不能冲突,它们可能存储在同一个引用数组中(感谢 Matthew)

$items; // array of item objects
// Use objects so they're implicitly passed by ref

$itemRef = array();

foreach ($items as $item) {
$itemRef[$item->unique_id] = $item;
$itemRef[$item->url] = $item;
}

// find by id
$byId = $itemRef[$id];

// find by url
$byUrl = $itemRef[$url];

您可以使用实现 getById()getByUrl() 的集合类很好地封装它。在内部,它可以根据需要将引用存储在尽可能多的数组中。

当然,您在这里所做的实际上是创建索引结果集,最好留给数据库管理系统。

关于php - 通过多个索引引用 PHP 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4405281/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com