具有动态值的 PHP 数组,其中包含稍后从 mysql 表构建选项值的项目列表

标签 php mysql arrays

我已经尝试解决这个问题有一段时间了,我对 PHP 很陌生,所以这可能很简单。 我现在有一个手动填充的数组,但我想根据 mysql 表中的数据使其动态化。

我的静态数组如下所示:

   $Prod1Array = [
                  ['NA', 'None'],
                  [10001, 'Prod1 Item1'],
                  [10011, 'Prod1 Item2'],
                  [10002, 'Prod1 Item3']
                  ];   

我的mysql表很简单,包含2列Product_code和Description。值如下所示:

10000, 'Product 1'
10001, 'Prod1 Item1'
10011, 'Prod1 Item2'
10002, 'Prod1 Item3'
10100, 'Product 2'
10101, 'Prod2 Item1'
etc...

所以我最终想要的是一个如下所示的数组:

$Products = [Product1Name
             ['NA', 'None'],
             [10001,'Prod1 Item1'],
             [10011,'Prod1 Item2'],
             [10002,'Prod1 Item3']
             ,
              Product2Name
             ['NA', 'None'],
             [10101,'Prod2 Item1'],
             [10102,'Prod2 Item2']
             ];

(也许我没有正确地想象这一点,但希望你明白) 基本上它是一个数组,顶层包含产品名称,子数组包含产品项。

根据给出的评论和答案,这就是我现在所拥有的:

$queryp = "select Description, Product_code from Products where Product_code like '___00' AND Product_code < 19999";
$resultp = queryMysql($queryp);

while($arr=mysqli_fetch_array($resultp))
{

$CODE = substr($arr[1],0,3) . '__';

$str1     =   "select Product_code, Description from Products where Product_code like'$CODE' AND Product_code <> $arr[1]";
$result1 =  queryMysql($str1);

while($arr1=mysqli_fetch_array($result1))
  {

      $arr[] = array($arr1);

  }
}

echo "<pre>";print_r($arr);echo"</pre>";

感谢“Ronser”,我已经很接近了,但我仍然缺少一些东西,因为最后的打印在数组中没有显示任何内容。

在代码的后面,我使用数组在表单中构建选项列表,它与静态数组一起工作得很好,但当然我想让代码更加动态,如果我添加新产品或更改mysql表中的描述,它会立即反射(reflect)在表单中。

现在,我的表单还具有产品列的静态标题,其想法是迭代数组的第一级以获取列标题,然后在表单表行中迭代不同的选项以获取列标题。创建列表(这与我的静态数组配合良好)。

我知道这是一个冗长的问题,感谢所有尝试回答甚至阅读本文的人。

最佳答案

使用sql非常简单 创建一个产品表(产品 ID、名称等)

项目表(在其中存储项目及其 ID、描述等)

在 items 表中使用诸如 fkpid 之类的列(此处存储产品选项卡中产品的 pid)

完成后

使用这个

$con    =   db_connect();   //first try this then add joins to the query.
$str    =   "select pid, pname from Products";
$result =   mysql_query($str,$con);

while($arr=mysql_fetch_array($result))
{
    echo "The product name is: ".$arr[1]. " and its items are:";

    $str1    =  "select iid, iname, idescription  from items 
                 where fkpid  = ".$arr[0];
    $result1 =  mysql_query($str1,$con); 

    while($itemsss=mysql_fetch_array($result1))
    {
         echo "<br>item name: ".  itemsss[1];
         echo "<br>item description".  itemsss[2]; // use `nl2br(itemsss[2])` inorder to have page breaks.              

    }

}

关于具有动态值的 PHP 数组,其中包含稍后从 mysql 表构建选项值的项目列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26280228/

相关文章:

php - MYSQL/PDO PHP系统---寻找大笔画输入

php - DATE php 和 mysql 唯一

mysql - 按值有效地将表连接(和更新)到最小/最大值范围

javascript - 为什么 AngularJS ng-model 返回 [object%20Object] 作为值而不是选项值(整数)?

php - 加入具有多个条件的两个表

php - 如何向带有外键的表中插入数据?

java - 基本的java : scanning files,数组

c++ - 这个未知大小数组的列表初始化在 C++0x 中有效吗?

php - 如何重新索引 MySQL 列?

php - 使用php mysql在二叉树中查找插入位置和子节点数