参考PHP数组由多个索引 [英] Reference PHP array by multiple indexes
本文介绍了参考PHP数组由多个索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这可能是某种怪异的长快捷方式,并请纠正我,如果我在这个思路错了...
This may be some sort of weird longer shortcut, and please correct me if I'm mistaken in this train of thought...
我有一个数据矩阵,看起来像:
I have a matrix of data that looks like:
unique_id | url | other random data...
unique_id | url | other random data...
unique_id | url | other random data...
我希望能够通过它要么是URL引用一个项目,或者它UNIQUE_ID - 有一个奇特的方式做到这一点?
I want to be able to reference an item by either it's url, or it's unique_id - is there a fancy way to do this?
我想作弊的解决办法是只是让两个数组,但我不知道是否有更好的方法。
I suppose the cheating solution would be to just make two arrays, but I was wondering if there is a better way.
推荐答案
尝试是这样的:
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
这篇关于参考PHP数组由多个索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文