1

我有 $str 字符串变量,我想从 $str 字符串创建一个 $array 数组。

    $str = "BKL|bkl,EXH|exh,FFV|ffv,LEC|lec,AUE|aue,SEM|sem";

    Final array should be 
    $array = array(
    'BKL'=> 'bkl',
    'EXH' => 'exh',
    'FFV' => 'ffv',
    'AUE' => 'aue'  
    );
4

5 回答 5

6

这应该可以解决问题

$str = "BKL|bkl,EXH|exh,FFV|ffv,LEC|lec,AUE|aue,SEM|sem";

$final = array();

foreach (explode(',', $str) as $pair) {
  list($key, $value) = explode('|', $pair);
  $final[$key] = $value;
}

print_r($final);

输出

Array
(
    [BKL] => bkl
    [EXH] => exh
    [FFV] => ffv
    [LEC] => lec
    [AUE] => aue
    [SEM] => sem
)
于 2013-01-08T06:30:12.163 回答
1

试试这个,

<?php
  $str = "BKL|bkl,EXH|exh,FFV|ffv,LEC|lec,AUE|aue,SEM|sem";

  $split = explode(',', $str);
  $arr = array();
  foreach($split as $v){
    $tmp = explode('|', $v);
    $arr[$tmp[0]] = $tmp[1];
  }

  print_r($arr);
?>

输出:

Array
(
    [BKL] => bkl
    [EXH] => exh
    [FFV] => ffv
    [LEC] => lec
    [AUE] => aue
    [SEM] => sem
)
于 2013-01-08T06:33:42.047 回答
1
$str = "BKL|bkl,EXH|exh,FFV|ffv,LEC|lec,AUE|aue,SEM|sem";

$result = array();
$node = explode(',', $str);

foreach ($node as $item) {
    $temp = explode('|', $item);
    $result[$temp[0]] = $temp[1];
}
于 2013-01-08T06:49:11.940 回答
0
$str = "BKL|bkl,EXH|exh,FFV|ffv,LEC|lec,AUE|aue,SEM|sem";
$out = array;
$arr = explode(',', $str);

foreach ($arr as $item) {
    $temp = explode('|', $item);
    $out[$temp[0]] = $temp[1];
}
于 2013-01-08T06:30:20.040 回答
0

你应该看看php手册中的explode

于 2013-01-08T06:32:08.323 回答