如何将此字符串分解为这样的数组?

时间:2011-07-06 10:23:30

标签: php arrays explode

我正试图打破这个字符串,

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

进入像这样的数组

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

因此语言的名称是关键,值是语言代码。这很简单,但我无法理解它。我已经从编程中扯下了太长时间,很明显......

我尝试在\n爆炸,然后使用foreach,再次在=爆炸,但我似乎无法按照我想要的方式将它拼凑起来。

4 个答案:

答案 0 :(得分:4)

  

我已尝试在\ n然后使用foreach爆炸,再次在“=”

爆炸

我认为这是正确的方法。

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

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

如果您希望语言为小写,例如您的示例($lang_codes['chinese']),则需要致电strtolower

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

有关这些功能的更多信息,请参阅PHP手册:

答案 1 :(得分:2)

虽然爆炸答案在技术上是正确的,但我立即认为您正在尝试解析INI文件。这是一种更简单的方法,可以完全满足您的需求。

<?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'];

答案 2 :(得分:0)

也许你应该这样做:

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

}

答案 3 :(得分: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>";
?>