开发者

converting string containing keys and values into array

开发者 https://www.devze.com 2023-01-22 00:38 出处:网络
does anyone know an elagant way of turning this string (the list is not definite.. the \"keys\" and \"values\" can be added arbitrarily)

does anyone know an elagant way of turning this string (the list is not definite.. the "keys" and "values" can be added arbitrarily)

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

into this array?

array(
     [business_type]=>'cafe'
     [business_typ开发者_如何学Goe_plural] => 'cafes'
     [sample_tag]=>'couch'
     [business_name]=>'couch cafe'
     )


Explode it!

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

This will output the following:

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

精彩评论

暂无评论...
验证码 换一张
取 消