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

时间:2010-10-27 12:41:33

标签: php arrays string

有没有人知道转动这个字符串的优雅方式(列表不明确......“键”和“值”可以任意添加)

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 个答案:

答案 0 :(得分:18)

爆炸!

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