将包含键和值的字符串转换为数组

8

有没有一种优雅的方法将此字符串转换为字典(列表不是固定的..可以随意添加“键”和“值”)

business_type,cafe|business_type_plural,cafes|sample_tag,couch|business_name,couch cafe

将它放入这个数组中?
array(
     [business_type]=>'cafe'
     [business_type_plural] => 'cafes'
     [sample_tag]=>'couch'
     [business_name]=>'couch cafe'
     )
1个回答

28

分裂它!

$string = "business_type,cafe|business_type_plural,cafes|sample_tag,couch|business_name,couch cafe";

$finalArray = array();

$asArr = explode( '|', $string );

foreach( $asArr as $val ){
  $tmp = explode( ',', $val );
  $finalArray[ $tmp[0] ] = $tmp[1];
}

print_r( $finalArray );

这将输出以下内容:

Array
(
    [business_type] => cafe
    [business_type_plural] => cafes
    [sample_tag] => couch
    [business_name] => couch cafe
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接