簡體   English   中英

PHP如何推送(累積)多維數組

[英]php how to push (accumulating) multidimensional array

請用多維數組推幫助。 請查看下面的代碼和注釋。 推送出現錯誤。 分配僅給出最后一行。

if (!isset($_SESSION['page_qstn_answer'])) {
$_SESSION['page_qstn_answer'] = array("page" => array(), "qstn" => array(), "answer" => array()
}
if (!isset($temp)) {
$temp = array("page" => array(), "qstn" => array(), "answer" => array() );
}
while($question = mysqli_fetch_assoc($question_set) ) {
if(isset($question['position']) ){
$post_qstn = $question['position'];
If(isset($_POST[$qstn]) ) {
//printing all rows from db correctly as below
//echo "Question ".$qstn." - selected answer  ".$answer . " on page ".$page ."<br />";
if (isset($temp) ){
$temp = array ("page"=>$page, "qstn"=>$qstn,"answer"=> $answer);}
//show a one by one array rows correctly but $temp has a one row at a time that is Ok
//print_r($temp);
// Try to accumulate $temp into $_Session array. Push is giving an error
//$_SESSION['pages_qstn_answers'] = array_push($_SESSION['pages_qstn_answers'], $temp);
// No error but no accumulation as foreach as below shows the only one last row.
$_SESSION['pages_qstn_answers'] = $temp;
}
foreach ($_SESSION['pages_qstn_answers'] as $key => $value) {
echo "$key = $value\n";}

我使用在網站上找到的函數來刪除所有以前添加的相同問題,然后再將$ temp條目累積到最終數組中,因為應該只有一個問題一個答案。 似乎可行。 如果有人在那里看到一些缺點,請提出建議。 謝謝

remove_elm($_SESSION['pages_qstn_answers'], "qstn", $qstn, TRUE);
$_SESSION['pages_qstn_answers'][] = $temp;
function remove_elm($arr, $key, $val, $within = FALSE) {
foreach ($arr as $i => $array)
if ($within && stripos($array[$key], $val) !== FALSE && (gettype($val) === gettype($array[$key])))
unset($arr[$i]);
elseif ($array[$key] === $val)
unset($arr[$i]);
return array_values($arr);
}

您對array_push()工作方式有誤解。 它不返回數組,而只是將其具有的任何值附加到數組中。 因此,當您這樣做時:

$_SESSION['pages_qstn_answers'] = array_push($_SESSION['pages_qstn_answers'], $temp);

等式的右側僅返回一個整數,其中包含新數組中元素的數量。 假設您數組中現在有5個元素,實際上就是

$_SESSION['pages_qstn_answers'] = 5;

而是做:

array_push($_SESSION['pages_qstn_answers'], $temp);

或者由於您只附加一個值,我會堅持:

$_SESSION['pages_qstn_answers'][] = $temp;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM