【问题标题】:Passing and receiving arrays in PhP在 PhP 中传递和接收数组
【发布时间】:2014-04-13 04:08:31
【问题描述】:

我正在尝试通过使用传递一个数组

$variables=questions_file='.($questions_file).'&questions_id='.($questions_id).'&count_hindi='.$count_hindi;
echo '<Redirect method="GET">startCall.php?'.$variables.'</Redirect>';

questions_file 和 questions_id 都是数组

foreach($question_records as $record=>$question)
                {
                    $questions_file[$i]=$question['file_name'].'_'.$question['concept_tested'];
                    $questions_id[$i]=$question['question_id'];
                    echo $questions_file[$i]. "\n";
                    $i++;
                }

因此,当我回显数组时,它会完美显示。但是当我使用上面的代码将它传递给另一个文件时,我尝试打印数组元素,它打印为空白。我尝试使用序列化和反序列化,但它仍然不起作用

我现在想通过使用检索值

$questions_id=(array)($_REQUEST['questions_id']);
$questions_file=(array)($_REQUEST['questions_file']);

但是当我尝试访问成员时。

使用时:

$questions_file= urldecode(http_build_query($questions_file));
            $questions_url= urldecode(http_build_query($questions_id));
            $url = $server.'/startCall.php?call_id='.$call_id.'&phone='.$phone.'&questions_id='.$questions_id.'&questions_file='.$questions_file.'&student_id='.$student_id.'&story='
            .$story.'&call_number='.$call_number.'&question_number=0&response=0&count_english=0&count_hindi=0';

我明白了

questions_file 0=q1_vocab&1=q3_comp&2=q5_crit&3=q7_gra

我想得到

questions_file[0]=q1_vocab&questions_file[1]=q3_comp&questions_file[2]=q5_crit&questions_file[3]=q7_gra

【问题讨论】:

  • 您能否详细说明“不工作”...?
  • 想知道是否有助于转义您的 $variables 字符串,以便正确传输 & 符号...
  • @RobP 如何转义变量,请检查我的更新回复

标签: php arrays get


【解决方案1】:

当你回显数组时,你只会得到“数组”这个词。所以你可能得到的是:

echo 'myArr=' . $myArr;
// myArr=Array

当您需要在 GET 中传递数组时,您需要显式定义它们。例如:

myArr[assoc]=1&myArr[assoc2]=2&myArr2[0]=1&myArr2[1]=2&myOtherArr[]=1

会给你:

$_GET['myArr'] -> ('assoc' => 1, 'assoc2' => 2)
$_GET['myArr2'] -> (0 => 1, 1 => 2)
$_GET['myOtherArr'] -> (0 -> 1)

幸运的是,PHP 为您提供了一个 built in function

$myArr = array('assoc' => 1, 'assoc2' => 2);
$get = array(
    'myArr' => $myArr,
    'myOtherArr' => array(1, 2)
);
echo urldecode(http_build_query($myArr));
// myArr[assoc]=1&myArr[assoc2]=2&myOtherArr[0]=1&myOtherArr[1]=2

【讨论】:

  • 如果我的程序动态初始化数组,所以我不知道有多少变量。我总是可以使用 for 循环创建参数字符串,但是手动方法更少吗?
  • 查看更新后的答案。即使它是动态的,您也可以将数组传递给该函数。但我不建议这样做,因为您将通过 GET 传递大量数据。您是否考虑过使用表单并通过 POST 提交?
  • 非常感谢......一旦我更改了我的代码并进行了测试,我将接受答案。真的有帮助!
  • 我收到 questions_file0=q1_vocab&1=q3_comp&2=q5_crit 而不是 questions_file[0]=q1_vocab&questions_file[1]=q3_comp&questions_file[2]=q5_cri。你能告诉我为什么吗?
  • 如何在使用上面的行之后检索数组元素..当我执行 echo questions_file 时,我得到 Array,当我执行 echo questions_file[0] 时,我得到空白作为输出
猜你喜欢
  • 2012-04-28
  • 1970-01-01
  • 1970-01-01
  • 2012-02-16
  • 1970-01-01
  • 2019-02-17
  • 2019-12-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多