【问题标题】:How to add or display dynamic array variables如何添加或显示动态数组变量
【发布时间】:2015-09-04 12:06:57
【问题描述】:

我正在将我的多维帖子变量转换为动态变量,如下所示:

foreach($_POST as $k => $v){
   ${$k} = $v;
}

所以我的新数组如下所示:

Array(
   [name] => Joe
   [surname] => Blogs
   [study] => Array
        (
            [0] => English
            [1] => IT
        )
   [school] => Array
        (
            [0] => Array
                (
                    [0] => Some School Name
                    [1] => 03/09/2015
                    [2] => Present
                )    
        )
)

因此,如果我想获取学校名称,则此代码将起作用:

echo $school[0][0];

但是,我很难在下面的 sql 语句中使用这个变量:

$sql = "INSERT INTO table (name, surname, subject_1, subject_2, school1_name, school1_datefrom, school1_dateto) VALUES ('$name', '$surname', '$subject[0]', '$subject[1]', '$school[0][0]', '$school[0][1]', '$school[0][2]', '$school[0][3]')";

echo $sql;

所有不是数组或单级数组(如study)的变量都显示得很好,但像$school[0][0] 这样的学校变量显示为'Array[0]'、'Array[1]'...。 ...... 为什么要这样做,是否可以让这些变量正确显示?

【问题讨论】:

    标签: php mysql sql arrays dynamic-programming


    【解决方案1】:

    如果您将数组值包装在{} 中,那么它应该可以正常工作。我不记得这背后的原因,但请尝试一下。

    $sql = "INSERT INTO table (name, surname, subject_1, subject_2, 
                               school1_name, school1_datefrom, 
                               school1_dateto) 
                  VALUES ('$name', '$surname', '{$subject[0]}', 
                          '{$subject[1]}', '{$school[0][0]}',
                           '{$school[0][1]', '{$school[0][2]}', 
                           '{$school[0][3]}')";
    

    我记得现在叫做复杂(卷曲)语法

    不是因为语法复杂,而是因为它允许使用复杂的表达式。

    【讨论】:

    • 谢谢,已经成功了。我认为为简单起见,我会将每个变量包含在一个大括号中,包括不是数组的变量,并且当我在 sql 查询中添加变量时,只需记住此语法作为规则
    【解决方案2】:

    替换

    $sql = "INSERT INTO table (name, surname, subject_1, subject_2, school1_name, school1_datefrom, school1_dateto) VALUES ('$name', '$surname', '$subject[0]', '$subject[1]', '$school[0][0]', '$school[0][1]', '$school[0][2]', '$school[0][3]')";
    

    $sql = "INSERT INTO table (name, surname, subject_1, subject_2, school1_name, school1_datefrom, school1_dateto) VALUES ('$name', '$surname', '{$subject[0]}', '{$subject[1]}', '{$school[0][0]}', '{$school[0][1]}', '{$school[0][2]}', '{$school[0][3]}')";
    

    【讨论】:

      【解决方案3】:

      将变量包装在 {} 中,它应该可以工作。花括号用于显式指定变量名的结尾。

      快点……

      $number = 4;
      print "You have the {$number}th edition book";
      //output: "You have the 4th edition book";
      

      没有花括号的 PHP 试图找到一个名为 $numberth 的变量,但它不存在!

      希望这会有所帮助。

      Ref.

      【讨论】:

        猜你喜欢
        • 2013-09-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-15
        • 2022-01-12
        相关资源
        最近更新 更多