开发者

How to explode this string into an array like this?

I'm trying to break up this string,

AFRIKAANS = af
ALBANIAN = sq
AMHARIC = am
ARABIC = ar
ARMENIAN = hy
AZERBAIJANI = az
BASQUE = eu
BELARUSIAN = be
BENGALI = bn
BIHARI = bh
BULGARIAN = bg
BURMESE = my
CATALAN = ca
CHEROKEE = chr
CHINESE = zh

Into an array like this

$lang_codes['chinese'] = "zh";

So the name of the language is the key, and the value is the lan开发者_StackOverflowguage code. This is really simple, but I just can't get my head around it. I've taken a brake from programming, too long, obviously...

I've tried exploding at \n then using a foreach, exploding again at = but I can't seem to piece it together the way I want.


I've tried exploding at \n then using a foreach, exploding again at " = "

I think this is exactly the right approach.

$lines = explode("\n", $langs);
$lang_codes = array();

foreach ($lines as $line) {
    list ($lang, $code) = explode(" = ", $line, 2);
    $lang_codes[$lang] = $code;
}

If you want the language to be in lowercase, as in your example ($lang_codes['chinese']), you'll need to call strtolower:

$lang_codes[strtolower($lang)] = $code;

See the PHP manual for more on these functions:

  • list
  • explode


Although the explode answers are technically correct, I immediately thought that you were trying to parse an INI file. Here's the simpler approach that does exactly what you want.

<?php
$string = "AFRIKAANS = af
ALBANIAN = sq
AMHARIC = am
ARABIC = ar
ARMENIAN = hy
AZERBAIJANI = az
BASQUE = eu
BELARUSIAN = be
BENGALI = bn
BIHARI = bh
BULGARIAN = bg
BURMESE = my
CATALAN = ca
CHEROKEE = chr
CHINESE = zh";

$array = array_change_key_case( parse_ini_string( $string ) );

echo $array['chinese'];


Mayb you shold do:

$array = explode("\n" , $string);
$finalArray =array();
$foreach ($array as $value){
      $array2 = explode( ' = ', $value);
      $finalArray[$array2[1]] =  $array2[0];

}


<?php 
$str ="AFRIKAANS = af
ALBANIAN = sq
AMHARIC = am
ARABIC = ar
ARMENIAN = hy
AZERBAIJANI = az
BASQUE = eu
BELARUSIAN = be
BENGALI = bn
BIHARI = bh
BULGARIAN = bg
BURMESE = my
CATALAN = ca
CHEROKEE = chr
CHINESE = zh";

$arr  = explode("\n", $str);
$lang_mapped = array();

foreach ($arr as $line) {
    list ($lang, $code) = explode(" = ", $line, 2);
    $lang_mapped[$lang] = $code;
}
$arr = explode("\n", $str); 
echo "<pre>";
print_r($lang_mapped);
echo "</pre>";
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜