简体   繁体   English

PHP:哈希数据库结果的最快方法?

[英]PHP: Quickest way to hash database result?

Let's say i do a query: 假设我进行查询:

select * from branches

Now, I get a result: 现在,我得到一个结果:

ID | CODE | Name  | etc...
1  | ABC  | One   | etc...
2  | BED  | Two   | etc...
3  | CPE  | Three | etc...
4  | FEE  | Four  | etc...

I will end up with an array that can be used like this: 我将得到一个可以像这样使用的数组:

$data[0]->name;

I want to change this array so I can call it like this: 我想更改此数组,因此可以这样称呼它:

$data['ABC']->name;

What is the quickest way to convert an array so that it's key is one of the items in the array? 转换数组以使其键为数组项之一的最快方法是什么? IePreferably without looping and assigning? 即最好不要循环和分配?

Simplest solution for this I think. 我认为这是最简单的解决方案。

$assoc = array();
$length = count($data);

for($i = 0; $i < $length; $i++) {
    $assoc[$data[$i]->CODE] = $data[$i]; 
}

print_r($assoc);

Although I believe there is a one line solution. 尽管我相信有一种解决方案。 Can't remember it off the top of my head however. 但是我不记得它了。

EDIT: 编辑:

Changed for loop condition, good call Raymond. 更改了循环条件,请致电Raymond。

Here is an in-line solution, if you really want to use compact code. 如果您确实想使用紧凑代码,则这是一种嵌入式解决方案。

However, I think this is way messier than a simple foreach loop. 但是,我认为这比简单的foreach循环更混乱。

$arr = array(your obj array);

$assoc = array();
array_walk($arr, function($v) {global $assoc; $assoc[$v->CODE]=$v;});

print_r($assoc);

Somewhere in your script you must be processing through a resultset and building this array so why not look back at that. 您必须在脚本中的某个位置处理结果集并构建此数组,所以为什么不回头看看呢。

What you are probably doing! 您可能正在做什么!

while ( $row = yourFetch ) {
    $data[] = $row;
endwhile;
return $data;

You could do this instead :- 您可以改为:

while ( $row = yourFetch ) {
    $data[$row->CODE] = $row;
endwhile;
return $data;

Then you dont have to add any processing after the event. 然后,您不必在事件之后添加任何处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM