这可能是某种奇怪的长快捷方式,如果我在思路上错了,请纠正我...
我有一个数据矩阵,看起来像:
unique_id | url | other random data...
unique_id | url | other random data...
unique_id | url | other random data...
我希望能够通过网址或唯一标识符引用一个项目 - 是否有更好的方法实现?
我想也可以采用两个数组的欺骗性解决方案,但我想知道是否有更好的方法。
这可能是某种奇怪的长快捷方式,如果我在思路上错了,请纠正我...
我有一个数据矩阵,看起来像:
unique_id | url | other random data...
unique_id | url | other random data...
unique_id | url | other random data...
我希望能够通过网址或唯一标识符引用一个项目 - 是否有更好的方法实现?
我想也可以采用两个数组的欺骗性解决方案,但我想知道是否有更好的方法。
我能想到的不需要为每次搜索迭代数组(参见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()
方法的集合类来封装这个功能。在内部,它可以使用需要的数组存储引用。
当然,你所做的基本上是创建索引结果集,这是最好留给数据库管理系统处理的事情。
$items
)。这可能会稍微有些混淆,但是Bob说键不会发生冲突。 - Matthew Flaschenfetch_both
方法检索数据库记录时一样,结果包含数字和字符串索引。说到索引,如果这些数据来自数据库,最好将ID和url字段应用索引,并执行单个提取以检索指定的记录。 - Philurl
映射到unique_id
的第二个数组更加清晰。保持不同的概念分开。 - ToolmakerSteve试试这样的代码:
function selectByIdOrURL($array, $data) {
foreach($array as $row) {
if($row['unique_id'] == $data || $row['url'] == $data) return $row;
}
return NULL;
}
$array = array(
array('unique_id' => 5, 'url' => 'http://blah.com'),
array('unique_id' => 3, 'url' => 'http://somewhere_else.com')
);
$found = selectByIdOrURL($array, 5); //array('unique_id' => 5, 'url' => 'http://blah.com')
$nfound = selectByIdOrURL($array, 10); //NULL
$items = [
[
'unique_id' => 42,
'url' => 'http://foo.com'
],
[
'unique_id' => 57,
'url' => 'http://bar.com'
],
[
'unique_id' => 36,
'url' => 'http://example.com'
],
];
$bar = $entries[array_search(57, array_column($items, 'unique_id'))];
var_dump($bar);
//outputs
array (size=2)
'unique_id' => int 57
'url' => string 'http://bar.com' (length=14)
肯定一个对象会更容易吧?
class Item {
public $unique_url;
public $url;
public $other_data;
public function __construct($unique_url, $url, $other_data)
{
$this->unique_url = $unique_url;
$this->url = $url;
$this->other_data = $other_data;
}
}
class ItemArray {
private $items = array();
public function __construct()
{
}
public function push(Item $item)
{
array_push($items, $item); //These may need to be reversed
}
public function getByURL($url)
{
foreach($items as $item)
{
if($item->url = $url)
{
return $item;
}
}
}
public function getByUniqueURL($url)
{
foreach($items as $item)
{
if($item->unique_url = $unique_url)
{
return $item;
}
}
}
}
然后与之一起使用
$itemArray = new ItemArray();
$item = new Item("someURL", "someUniqueURL","some other crap");
$itemArray->push($item);
$retrievedItem = $itemArray->getItemByURL("someURL");
这种技术由于对象创建而带有一些额外的开销,但除非你处理的行数非常大,否则它是可以接受的。
unique_id
映射到“其他随机数据”,然后再有一个数组将url
映射到unique_id
。这就是unique_id
的目的:提供一个简洁高效的“句柄”,代表给定记录(行)的数据。 - ToolmakerSteve