2010-10-10 195 views
0

我想 轉換這個字符串:將字符串轉換多維數組

$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

已經有** ** 7和意見** 4 **回答截至目前:) – codaddict 2010-10-10 04:28:44

回答

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

Link to code

+0

謝謝你,這似乎是最優雅的解決方案 – ondrobaco 2010-10-10 04:36:58

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

可以使用explode爲做到這一點;

$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