views:

38

answers:

3

hi, 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?

A: 
$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];
}
parent5446
+3  A: 

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]);
}

Working link

codaddict
+2  A: 

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

Link to code

Galen
thank you this seems to be the most elegant solution
ondrobaco