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 :)
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.
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);
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.
No. Arrays can only have integers and strings as keys.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With