将数据存储到三维数组PHP中

时间:2019-07-18 08:00:26

标签: php mysql arrays

我有一组存储在数据库表%中的数据,如下所示:

tb_Alt

id_alt |name|distance|price|quantity 1 |A | 2 | 10 | 3 2 |B | 4 | 123 | 4 3 |C | 1 | 201 | 1 4 |D | 5 | 145 | 10 如下:

tb_Cri

现在,我想将数据从id_criteria |name | weight | 1 |distance | 10 2 |price | 20 3 |quantity | 30 动态插入到tb_A中,结构如下:

tb_B

如何通过PHP实现此目标?

这是我到目前为止所尝试的:

# |id_alt | id_criteria | value 
1 | 1     |   1         |  2
2 | 1     |   2         |  10
3 | 1     |   3         |  3
4 | 2     |   1         |  4
5 | 2     |   2         |  123
6 | 2     |   3         |  4
7 | 3     |   1         |  1
8 | 3     |   2         |  201
9 | 3     |   3         |  1
10| 4     |   1         |  5
11| 4     |   2         |  145
12| 4     |   3         |  10

1 个答案:

答案 0 :(得分:0)

INSERT INTO tab_b (name,value)
  SELECT name,value FROM (
    SELECT id, 1 as id2, name,distance as value FROM tb_A
      UNION SELECT id, 2 as id2, name,price as value FROM tb_A
      UNION SELECT id, 3 as id3, name,quantity as value FROM tb_A
    ORDER BY id, id2
  ) t;

始终最好在数据库计算live example @ SQL Fiddle

中使用