I'd like to convert this string:
$credit_packages_string = "300,0.25|1000,0.24|3000,0.22|4000,0.20|5000,0.18|6000,0.16|7000,0.14";
into this array:
$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)
);
how would you do it in a most efficient way?
asked Oct 10, 2010 at 4:14
ondrobaco
7374 gold badges13 silver badges24 bronze badges
-
There have been 7 views and 4 answers as of now :)codaddict– codaddict2010年10月10日 04:28:44 +00:00Commented Oct 10, 2010 at 4:28
3 Answers 3
You can do it using 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]);
}
answered Oct 10, 2010 at 4:20
codaddict
457k83 gold badges503 silver badges538 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Without using regular expression you'll need some loops so using a regex may be best
$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);
answered Oct 10, 2010 at 4:26
Galen
30.2k9 gold badges75 silver badges90 bronze badges
Comments
$array = explode(',', explode('|', $credit_packages_string));
This would only give you a numerical array. If you really want the 'credit_amount' and 'price_per_credit' keys, add the following:
foreach($i as &$array) {
$i['credit_amount'] = $i[0];
$i['price_per_credit'] = $i[1];
}
answered Oct 10, 2010 at 4:20
parent5446
8988 silver badges17 bronze badges
Comments
Explore related questions
See similar questions with these tags.
lang-php