简体   繁体   中英

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.

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.

$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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