ondrobaco
ondrobaco

Reputation: 737

converting string into multidimensional array

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?

Upvotes: 0

Views: 2899

Answers (3)

Galen
Galen

Reputation: 30170

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

Upvotes: 3

codaddict
codaddict

Reputation: 454960

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

Upvotes: 4

parent5446
parent5446

Reputation: 898

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

Upvotes: 1

Related Questions