2013-08-28 85 views
7

//返回從問題表如何將數組存儲到一個會話變量在PHP

$result = mysqli_query($con,"SELECT question FROM questions ORDER BY rand() LIMIT 10' "); 
while($row = mysqli_fetch_row($result)) 
{ 
$que[]=$row[0]; 
} 

10問題,現在我需要這一整套$que[]存儲在一個會話變量。 (即10題)

像這樣的事情

$_SESSION['question'] = $que[]; 

$my_array[] = $_SESSION['question']; 

使$my_array[0]回到第一個問題,$my_array[1]收益第二的問題和這樣。

(感謝名單提前爲幫助)

+1

剛'$ _SESSION ['question'] = $ que;'no [] – 2013-08-28 22:10:02

回答

10

分配

$_SESSION['question'] = $que; 

print_r($_SESSION['question'][0]);會給你的第一個問題。

+1

將使用echo代替print_r有什麼不同? – Gokigooooks

5

你幾乎是正確的,你只需要添加到數組時需要的[]

$_SESSION['question'] = $que; 

請確保您有一個會議要首先,在你的腳本的頂部放置此,如果一個已經不將啓動一個會話中:

if(!isset($_SESSION)) { 
    session_start(); 
} 

把它備份:

$array = $_SESSION['question']; //Assigns session var to $array 
print_r($array);     //Prints array - Cannot use echo with arrays 


最終加入

要遍歷數組,您通常可以使用for或foreach。對於語句,只有當數組鍵是增量式(0,1,2,3等)時沒有任何間隙才能正常工作。

for($x = 0, $max = count($array); $x < $max; ++$x) { 
    echo $array[$x]; 
} 

foreach($array as &$value) { 
    echo $value; 
} 

這兩個都是爲了表現而寫的。知道使用參考時非常重要(&$value,請注意&)如果編輯參考,原始值會更改。如果不按參考使用,則會創建該值的副本。因此,例如:

//Sample Array 
$array = array('0' => 5, '1' => 10); 


//By Reference 
foreach($array as &$value) { 
    $value += 2;    //Add 2 to each value 
    echo $value;    //Echos 7 and 12, respectively 
} 
print_r($array); //Now equals array('0' => 7, '1' => 12) 


//Normal Method 
foreach($array as $value) { 
    $value += 2;    //Add 2 to each value 
    echo $value;    //Echos 7 and 12, respectively    
} 
print_r($array); //Still equals array('0' => 5, '1' => 10) 

參考更快,但如果你是刨,同時保持原有的陣列完好修改值。

+0

不工作:/它返回的只是'Array' – Aayush

+0

我該如何訪問那些存儲在session中的值? – Aayush

+0

Ohkay沒有迴音與陣列! 實際上,我希望打印$ my_array [0],$ my_array [1],$ my_array [2] .... $ my_array [10]?如何通過printf使它成爲可能? – Aayush

2

使用

session_start(); 
$_SESSION['question'] = $que; 
&que = array(an array of your 10m question s); 

當你想將它命名另一頁上獲得一個排隊的你的問題,使用

while (list($key, $value) = each($_SESSION)) { 
#Echo the questions using $key 
    echo "Here is a list of your questions"; 
    echo "<br/>"; 
    while (list($key2, $value2) = each($_SESSION)) { 
#$value2 show's name for the indicated ID 
#$key2 refers to the ID 
     echo "<br/>"; 
     echo "Question: ".$value2." "; 
     echo "<br/>"; 
    } 
    echo "<br/>"; 
} 

,或者您也可以使用

print_r;