简体   繁体   中英

How to create particular array from string in php

I Have $str string variable & i want to make a $array array from $str string.

    $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'  
    );

This should do the trick

$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);

Output

Array
(
    [BKL] => bkl
    [EXH] => exh
    [FFV] => ffv
    [LEC] => lec
    [AUE] => aue
    [SEM] => sem
)

Try this,

<?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);
?>

Output:

Array
(
    [BKL] => bkl
    [EXH] => exh
    [FFV] => ffv
    [LEC] => lec
    [AUE] => aue
    [SEM] => sem
)
$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];
}
$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];
}

您应该在php手册中查看explode

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