简体   繁体   English

如何在一维数组中分配键名

[英]How to assign key name in a single dimensional array

I'm trying to assign country code as key, country name as value. 我正在尝试将国家/地区代码指定为键,将国家/地区名称指定为值。 The following is my code, if any wrong please correct me. 以下是我的代码,如果有任何错误,请纠正我。

$return = array();
foreach($result as $key=>$value){
    array_splice($return, count($return),0, array($value['country_code']=>$value["name"]));
}

it looks like this would suffice: 看起来就足够了:

$return = array_column($result, 'name', 'country_code');

this is essentially a shorter version of 这本质上是

foreach($result as $key => $value){
    $return[$value['country_code'] ] = $value["name"];
}

Iterate the $result to set the value. 迭代$ result以设置值。

foreach($result as $v)
{
  $return[$v['country_code']] = $v['name'];
}

here one more approach using array_map() : 这是使用array_map()的另一种方法:

$modified = array_map(function($result){    
    return [$result['country_code'] => $result['name']];
}, $resultset);

Cheers! 干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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