简体   繁体   中英

How to create an associative array using a 2 dimentional array in php?

How can i create an associative array using the array below, In the fastest and shortest way.

$list = array(array('name', 'aram'), array('family', 'alipoor'));

Something like:

$list = array('name' => 'aram', 'family' => 'alipoor');
$assocArray = array();

foreach($list as $subArray)
{
    $assocArray[$subArray[0]] = $subArray[1];
}

The shortest I can think of:

$newlist = array();
foreach ( $list as $keyval ) {
    $newlist[ $keyval[0] ] = $keyval[1];
}

Terrible approach, but

$lst = array_combine(array_map('array_shift',$list), array_map('array_pop',$list));

Works only for two-element inner arrays.

Note: three implicit loops in this solution. So better use approach from Rijk van Wel or kevinmajor1 answer

I generally think foreach is pretty well readable and normally pretty fast. If you want it in one line, you can do with foreach as well:

$nl = array(); foreach($list as $k=>$v) $nl[$k]=$v; $list = $nl; unset($nl);

Which is basically demonstrating that there is no value in getting something "single line".

Or if you prefer callbacks for some reason I don't know of:

$list = array_reduce($list, function($v,$w) {return $v+array($w[0]=>$w[1]);}, array());

Which demonstrates that as well. It will hardly be faster than foreach, in any case, the speed differences most certainly do not matter in your case.

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