简体   繁体   English

用PHP将数组值分配给增量变量以插入到mysql表中

[英]Assigning array values to incremental variables with PHP to insert into mysql table

I have the following results page from the previous form: 我具有来自先前表单的以下结果页面:

<?php
//Get the form results (which has been converted to an associative array) from the $_POST super global
$musicgenres = $_POST['music'];

//Sort the values by rank and keep the key associations.
asort($musicgenres, SORT_NUMERIC );

//Loop over the array in rank order to print out the values.
foreach($musicgenres as $music => $rank)
{
    echo "$music is your $rank choice";
   echo "<br>";
 }
?>

Here is an example of the output (without the bullets): 这是输出示例(不带项目符号):

  • Rap is your 1 choice 说唱是您的第一选择
  • Rock is your 2 choice 摇滚是您的2选择
  • Jazz is your 3 choice 爵士乐是您的3种选择
  • etc.... 等等....

I'm thinking that putting this into a table will not be easy or clean. 我认为将其放到桌子上既不容易也不容易。 How can assign these values to incremental variables? 如何将这些值分配给增量变量?

eg 例如

  • $musicrank1 = rap $ musicrank1 =说唱
  • $musicrank2 = rock $ musicrank2 =摇滚
  • $musicrank3 = jazz $ musicrank3 =爵士乐
  • etc.... 等等....

Try this 尝试这个

$i = 0;
//Loop over the array in rank order to print out the values.
foreach($musicgenres as $music => $rank)
{
    ${ "musicrank". ($i) }  =   $music;
    echo "$music is your $rank choice";
   echo "<br>";
   $i++;
 }

after foreach you'll have your variables. 在foreach之后,您将拥有变量。

Using a table is much easier than creating arbitrary variables. 使用表比创建任意变量容易得多。 With the table you just have to say $musicrank[1] instead of $musicrank1 and you can iterate over the table if you want to. 使用表时,您只需要说$musicrank[1]而不是$musicrank1 ,就可以遍历表。

As a rule of thumb, if you'd assign each value in the table manually, you should use variables instead. 根据经验,如果您要手动分配表中的每个值,则应改用变量。 But you are using a loop, so it's a pretty obvious case for tables. 但是您正在使用循环,因此对于表来说这是很明显的情况。

use this script : for add array with comma 使用此脚本:使用逗号添加数组

        `$no = 0;
        foreach($sql2 as $row2)
        {
            $row["store_name"] .= ($no != 0) ? ", " : "";
            $row["store_name"] .= $row2["store_name"];

            $no++;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM