猿问

如何声明和使用全局变量

在此测试页面https://wintoweb.com/sandbox/question_2.php 上,访问者可以在数据库中进行搜索并根据需要勾选任意数量的复选框。当单击按钮 [接受...] 时,我希望所有搜索的结果都显示在“到目前为止您的选择”下。现在,只显示最后一次搜索。我尝试使用全局数组来存储先前搜索的结果并在每次新搜索时增加它。这就是我有问题的地方。


在文件顶部我有:


<?php

    global $all_authors;

    array ($all_authors, '');

?>

在文件底部我有:


<?php

error_reporting(E_ALL);

ini_set('display_errors', true);


if(isset($_GET['search'])){

    //echo 'Search</br>';

} elseif(isset($_GET['display_this'])) {

    echo getNames();

}


function getNames() {

    $rets = '';

    if(isset($_GET['choices']) and !empty($_GET['choices'])){

      foreach($_GET['choices'] as $selected){

        $rets .= $selected.' -- ';

      }

//array_push($all_authors, $rets); // This is the problem

//print_r($allAuthors); // this too

echo '</br><b>Your selections so far :</b></br>';

    }

    return $rets;

}

?>

预期:要列出所有先前搜索的结果 实际:由于 array_push() 问题,无法进行。参见函数 gatNames()


慕莱坞森
浏览 173回答 2
2回答

牧羊人nacy

你正在$rets从你的getNames函数中返回,但没有使用它。你只需要使用这个变量$rets而不是全局变量。if(isset($_GET['search'])){&nbsp; &nbsp; //echo 'Search</br>';} elseif(isset($_GET['display_this'])) {&nbsp; &nbsp; $rets = getNames(); //The $rets will hold the value returned by your function getName().&nbsp;&nbsp; &nbsp; if( !empty ( $rets ) ) {&nbsp; &nbsp; &nbsp; &nbsp;echo '</br><b>Your selections so far :</b></br>';&nbsp; &nbsp; &nbsp; &nbsp;echo $rets;&nbsp; &nbsp; }}您可以从getNamesMethod 中删除 echo 语句。function getNames() {&nbsp; &nbsp; $rets = '';&nbsp; &nbsp; if(isset($_GET['choices']) and !empty($_GET['choices'])){&nbsp; &nbsp; &nbsp; foreach($_GET['choices'] as $selected){&nbsp; &nbsp; &nbsp; &nbsp; $rets .= $selected.' -- ';&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return $rets;}

SMILET

您应该在函数内部使数组全局化,因此最重要的是:$all_authors = array();在底部:function getNames() {&nbsp; &nbsp; global $all_authors;&nbsp; &nbsp; // Do the rest of the stuff}
随时随地看视频慕课网APP
我要回答