2015-09-04 111 views
1

我将我的多维后变量动态变量如下:如何添加或显示动态数组变量

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语句iable象下面这样:

$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]被显示为“数组[0]”,“阵列[1]'......... 它为什么这样做,并且在那里我可以让这些变量正确显示?

回答

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]}')"; 

我现在还记得被称为复合物(花)语法

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

+0

谢谢,已经奏效。我认为为了简单起见,我会将每个变量包含在一个大括号内,包括不是数组的变量,并且当我在sql查询中添加变量时,只记得这个语法作为规则 – Ahm3d

0

将变量包装在{},它应该工作。大括号用于明确指定变量名称的结尾。

快速...

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

Wihtout花括号PHP尝试找到一个名为$ numberth变量,即不存在的!

希望这有助于。

Ref.

0

更换

$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]}')";