2013-11-22 45 views
-1

問題:轉換字符串中MySQL表字段到陣列中PHP

我在我的MySQL表具有以下值的字段:

9,10,11,12,13,14, 15,16,26,27,28,29,30,31,32

我用PHP把這個字段的值放在變量中:$ row ['Exclude'];

的問題是,我使用的是看起來下面的一個函數調用rand_except():

function rand_except($min, $max, $except) 
{ 
    //first sort array values 
    sort($except, SORT_NUMERIC); 

    //calculate average gap between except-values 
    $except_count = count($except); 
    $avg_gap = ($max - $min + 1 - $except_count)/($except_count + 1); 

    if ($avg_gap <= 0) 
    return false; 

    //now add min and max to $except, so all gaps between $except-values can be calculated 
    array_unshift($except, $min - 1); 
    array_push($except, $max + 1); 
    $except_count += 2; 

    //iterate through all values of except. If gap between 2 values is higher than average gap, 
    // create random in this gap 
    for ($i = 1; $i < $except_count; $i++) 
     if ($except[$i] - $except[$i - 1] - 1 >= $avg_gap) 
     return mt_rand($except[$i - 1] + 1, $except[$i] - 1); 
    return false; 
} 

爲了這個工作,它需要是這樣的:

$exclude = array(9, 10, 11, 12, 13, 14, 15, 16, 26, 27, 28, 29, 30, 31, 32);  
$_SESSION['experimentversion'] = rand_except(1, 32, $exclude); 

問題:

我該如何取數據庫字段$ row ['Exclude']並將其轉換爲數組,以便它將使用該功能?

回答

1

簡單。使用爆炸功能。

$s = "1,2,3,4"; 
$y = explode(",", $s); 
print_r($y) 
+0

不行的,它只會隨機化1-8之間的數字並忽略17-25。不知道爲什麼。 rand_except有問題嗎? – kexxcream

+0

你能告訴我你的函數rand_except到底應該做什麼?我的意思是這個功能的目的是什麼? – Romit

+0

我已經解決了,我用這個函數來代替:http://stackoverflow.com/questions/2698265/how-to-get-a-random-value-from-1n-but-excluding-several-specific-values-在-PHP – kexxcream

1
$exclude = explode(', ', $row['Exclude']); 
1
$str = '1,2,3,4,5'; 
$arr = explode(",",$str); 
print_r($arr); 
1

這應該做的伎倆:

$exclude = explode(", ", $row['Exclude']); 
1

使用爆炸功能。對於更多的信息爆炸Visi this link

$row = "retrive your value from db"; 
$data = explode(", ",$row); 
print_r($data); //here you will get array of your db field 
1

PHP中一個爆炸方法,你可以用這個方法

$string = '1,2,3,4,5'; 
$array = explode(",",$string); 
print_r($array); 
it will create an array.