请帮助多维数组推送。请参阅下面的代码和评论。推送是错误的。分配仅给出最后一行。
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";}
答案 0 :(得分:0)
我使用了我在网站上找到的一个函数来删除所有先前添加的相同问题,然后将$ 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);
}
答案 1 :(得分:-1)
您对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;