我想 转换此字符串:
$credit_packages_string = "300,0.25|1000,0.24|3000,0.22|4000,0.20|5000,0.18|6000,0.16|7000,0.14";
进入这个数组:
$credit_packages = array( array( 'credit_amount'=> 300,
'price_per_credit'=>0.25),
array( 'credit_amount'=> 1000,
'price_per_credit'=>0.24),
array( 'credit_amount'=> 3000,
'price_per_credit'=>0.22),
array( 'credit_amount'=> 4000,
'price_per_credit'=>0.20),
array( 'credit_amount'=> 5000,
'price_per_credit'=>0.18),
array( 'credit_amount'=> 6000,
'price_per_credit'=>0.16),
array( 'credit_amount'=> 7000,
'price_per_credit'=>0.14)
);
你会如何以最有效的方式做到这一点?
答案 0 :(得分:4)
您可以使用explode
as;
$result = array();
$credits = explode('|',$credit_packages_string);
foreach($credits as $credit) {
$credit_part = explode(',',$credit);
$result[] = array('credit_amount' => $credit_part[0],
'price_per_credit' => $credit_part[1]);
}
答案 1 :(得分:3)
不使用正则表达式,你需要一些循环,所以使用正则表达式可能是最好的
$credit_packages_string = "300,0.25|1000,0.24|3000,0.22|4000,0.20|5000,0.18|6000,0.16|7000,0.14";
preg_match_all( '~(?P<credit_amount>\d+),(?P<price_per_credit>[\d\.]+)~', $credit_packages_string, $matches, PREG_SET_ORDER );
print_r($matches);
答案 2 :(得分:1)
$array = explode(',', explode('|', $credit_packages_string));
这只会给你一个数值数组。如果您真的需要'credit_amount'和'price_per_credit'键,请添加以下内容:
foreach($i as &$array) {
$i['credit_amount'] = $i[0];
$i['price_per_credit'] = $i[1];
}