如何在while循环中获取列的所有值并将这些值放入数组中

时间:2017-08-14 06:51:07

标签: php mysql

下面我有一个显示MySQL数据的表,在数据库中,有三列用于存储不同语言的msg(即传统消息, 简化消息和工作)。

每个人都可以选择他们的首选语言,在view page中,有一个msg column,它会显示人们的首选语言信息

喜欢这个

 People      Language       Msg
 A            繁體           物理治療
 B            Eng           Physiotherapy
 <table>

  <?php
 $result = mysql_query("SELECT * 
 FROM treatmentdetail WHERE
 language ='繁體' OR language ='ENG' OR language ='简体'");?>
 <?php

  $specific = [];

  while($row = mysql_fetch_array( $result ,MYSQL_ASSOC)) {?>

  <tr>

  <td><input class="form-control" type="text" size="1" name="people[]"  
  value="<?php echo $row['people'] ?>"></td>
  <td><input class="form-control" type="text" size="1" name="language[]"  
  value="<?php echo $row['language'] ?>"></td>


  <td width="200px"><input class="form-control" type="text" size="1" 
  name="msg[]" value="
  <?php if($row['language'] == '繁體')
  {
  echo  $row['traditionalmessage'];}

  else if($row['language'] == 'ENG')
  {
  echo $row['engmessage'];}

  if($row['language'] == '简体')
  {
  echo  $row['simplifiedmessage'];} ?>">
  </td>

关闭表格

 <?php
echo "</tr>";
echo "</table>";echo "</form>";?>

现在我想get all the values of the msg column并将它们放在一个名为$ specific

的数组中
     <?php $specific = [
                       "message" => $row["engmessage"]
                   ];?>

这里我只是硬编码以获取所有消息的值。但是,因为有传统的消息和&amp;简化消息。所以它必须是动态的。

那么如何获取msg列的所有值(可能具有从多个数据库列中检索的值

i.e. traditionalmessage/
simplifiedmessage /engmessage) 

并将这些值放入数组

希望你明白我的意思。

非常感谢。

2 个答案:

答案 0 :(得分:1)

What problem? As I understand you need to extract all columns with message and loop by them. You know all column names or you need to determine it dynamically? If you know it before, you can loop over $row array and extract needed values into an array.

    foreach ($row as $key) {
        //ignore columns with no 'message' in title
        if (FALSE === strpos($key, 'message')) continue;

        // do with $row[$key] what you want
    }

As respected member Strawberry said you need to use mysqli (mysql improved or pdo, or mysqlnd) extension to work with DB instead of deprecated and obsolete mysql extension.

General advice You table structure is wrong if you need to add new columns for each new language. You need to rethink you table structure. Google about 'db normalisation'.

答案 1 :(得分:0)

我可以使用if else语句获得我想要的结果。我知道那里肯定有更好的答案。如果你碰巧有一个,请分享。再次感谢那些一直帮助过的人。

 if($row['language'] == '繁體')
 {
  $specific[] = [
                 "message" => $row["traditionalmessage"]

 ];}

  else if($row['language'] == '简体')
 {
  $specific[] = [
                 "message" => $row["simplifiedmessage"]          

 ];}

  else if($row['language'] == 'ENG')
  {
  $specific[] = [
                 "message" => $row["engmessage"]

 ];}