0

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?

1
  • There have been 7 views and 4 answers as of now :) Commented Oct 10, 2010 at 4:28

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1
$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];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.