2013-07-02 111 views
0

我正在使用具有動態數組的類。我需要將這些類的動態數組的結果存儲在數據庫中。如何將類對象數組值存儲到數據庫中並從數據庫中檢索這些值

<?php 
require_once('ag.php'); 
class H 
{ 
    var $Voltage; 
    var $Number; 
    var $Duration; 
function H($Voltage=0,$Number=0,$Duration=0) 
    { 
     $this->Voltage = $Voltage; 
     $this->Number = $Number; 
     $this->Duration = $Duration; 
    }} 
//This will be the crossover function. Is just the average of all properties. 
function avg($a,$b) { 
return round(($a*2+$b*2)/2); 
} 
//This will be the mutation function. Just increments the property. 
function inc($x) 
{ 
    return $x+1*2; 
} 
//This will be the fitness function. Is just the sum of all properties. 

function debug($x) 
{ 
    echo "<pre style='border: 1px solid black'>"; 
    print_r($x); 
    echo '</pre>'; 
    } 
//This will be the fitness function. Is just the sum of all properties. 
function total($obj) 
{ 
return $obj->Voltage*(-2) + $obj->Number*2 + $obj->Duration*1; 
} 
$as=array(); 
for($i=0;$i<$row_count;$i++) 
{ 
$adam = new H($fa1[$i],$fb1[$i],$fcc1[$i]); 
$eve = new H($fe1[$i],$ff1[$i],$fg1[$i]); 
$eve1 = new H($fi1[$i],$fj1[$i],$fk1[$i]); 
$ga = new GA(); 
echo "Input"; 
$ga->population = array($adam,$eve,$eve1); 
debug($ga->population); 
$ga->fitness_function = 'total'; //Uses the 'total' function as fitness function 
$ga->num_couples = 5;    //4 couples per generation (when possible) 
$ga->death_rate = 0;    //No kills per generation 
$ga->generations = 10;    //Executes 100 generations 
$ga->crossover_functions = 'avg'; //Uses the 'avg' function as crossover function 
$ga->mutation_function = 'inc';  //Uses the 'inc' function as mutation function 
$ga->mutation_rate = 20;   //10% mutation rate 
$ga->evolve();      //Run 
echo "BEST SELECTED POPULATION"; 
debug(GA::select($ga->population,'total',3)); //The best 
$as=array((GA::select($ga->population,'total',3))); //The best 
} 
?> 

$as是包含我需要在數據庫中存儲該值的數組。請幫助我。這個$as數組在計算後包含$adam,$eve,$eve1的值。

回答

0

要存儲在數據庫中的數組,當你從數據庫中檢索它使用unserialize

$back_to_array = unserialize($result_from_database); //You now have the array again 

還要考慮使用PHP5符號類的聲明,你可以使用PHP serialize功能

$serialized_array = serialize($as); // This can now be stored in the database 

然後如聲明函數和成員變量爲public/protected/private並使用function __construct()代替function your_class_name

+0

sir我該如何寫這個查詢意味着想知道列的名字 – ashy1234

0
<?php 

//serialize and store the value into the database 

//however to storing the object into the db is not good practice 
$val = serialize($$as); 

$sql = "insert into table_name field_name values('$val')"; 

//execute the query 
$query = mysqli_query($connection_variable, $sql) or die('error in query'); 


//while retrieving use unserialize($str) function 
unserialize($val); 
+0

我該如何編寫關於mysql函數的更多細節的查詢 – ashy1234

+0

http://www.php.net/manual/en/ mysqli.quickstart.statements.php – Sundar

+0

字段名稱是一個或輸出的數字我在數組中獲得$屁股意味着我有9個輸出值在它 – ashy1234

相關問題