我正在尝试分离具有多个值的字符串,这些字符串之间用;分隔;每个值和键之间用|分隔。我理想的情况是希望最终看起来像这样:
$array = array(
array( "qty" => "2", "code" => "YQTWEY33" ),
array( "qty" => "1", "code" => "YQTWEY53" )
)
我将字符串包含在名为$ str的变量中,并且使用爆炸功能来分离出不同的值。但是,我不确定从这儿去哪里。有人可以帮忙吗?
$str = "qty: 2 | code: YQTWEY33; qty: 1 | code: YQTWEY53";
$topics = array();
foreach (explode(';', $str) as $topic) {
list($name, $items) = explode('|', $topic);
$topics[$name] = explode(':', $items);
print_r($topics);
}
答案 0 :(得分:1)
$str = "qty: 2 | code: YQTWEY33; qty: 1 | code: YQTWEY53";
$topics = array();
foreach (explode(';', $str) as $index=> $topic) {
foreach(explode('|', $topic ) as $item ) {
list($key, $value) = explode(':', $item);
$topics[$index][trim($key)] = trim($value);
}
}
print_r($topics);