Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use array values as keys without loops?

Tags:

Looping is time consuming, we all know that. That's exactly something I'm trying to avoid, even though it's on a small scale. Every bit helps. Well, if it's unset of course :)

On to the issue

I've got an array:

array(3) {     '0' => array(2) {         'id'   => 1234,         'name' => 'blablabla',     },     '1' => array(2) {         'id'   => 1235,         'name' => 'ababkjkj',     },     '2' => array(2) {         'id'   => 1236,         'name' => 'xyzxyzxyz',     }, } 

What I'm trying to do is to convert this array as follows:

array(3) {     '1234' => 'blablabla',     '1235' => 'asdkjrker',     '1236' => 'xyzxyzxyz', } 

I guess this aint a hard thing to do but my mind is busted right now and I can't think of anything except for looping to get this done.

like image 271
Peter Avatar asked Jul 03 '15 09:07

Peter


People also ask

How do you find the value of an array without a loop?

Either use array_column() for PHP 5.5: $foo = array(["type"=>"a"], ["type"=>"b"], ["type"=>"c"]); $result = array_column($foo, 'type'); Or use array_map() for previous versions: $result = array_map(function($x) { return $x['type']; }, $foo);

How do you get an array key?

The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.

Can an array have keys?

No. Arrays can only have integers and strings as keys.

Can array key be an array?

As array values can be other arrays, trees and multidimensional arrays are also possible. And : The key can either be an integer or a string.


1 Answers

Simply use array_combine along with the array_column as

array_combine(array_column($array,'id'), array_column($array,'name')); 

Or you can simply use array_walk if you have PHP < 5.5 as

$result = array(); array_walk($array, function($v)use(&$result) {     $result[$v['id']] = $v['name'];  }); 

Edited:

For future user who has PHP > 5.5 can simply use array_column as

array_column($array,'name','id'); 

Fiddle(array_walk)

like image 164
Narendrasingh Sisodia Avatar answered Sep 28 '22 12:09

Narendrasingh Sisodia