Reputation: 13527
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? I.e.Preferably without looping and assigning?
Upvotes: 0
Views: 129
Reputation: 6946
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.
Upvotes: 4
Reputation: 18861
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);
Upvotes: 1
Reputation: 94642
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.
Upvotes: 0