如何将一个具有相同值的php数组拆分并插入到两个具有唯一值的mysql关系表中


How to split and insert a php array with some identical values into two mysql relational tables with unique values

我有这个php$array:

usr_id | value 1 | value 2 | value 3
1      |    a    |    b    |   c
2      |    a    |    b    |   c
7      |    d    |    e    |   f
8      |    a    |    e    |   f

我想把它分成两个具有唯一组合值的关系表:

表1>值

id | value1 | value2 | value3
1  | a      | b      | c
2  | d      | e      | f
3  | a      | e      | f

表2>关系

id | usr_id | values_id 
1  |    1    | 1
2  |    2    | 1
3  |    7    | 2
4  |    8    | 3

最简单的方法是什么?

提前非常感谢!

我的第一个想法是对php数组进行两次遍历。一次创建值表,然后再次创建关系表。可能有一种方法只需一次传球就可以做到这一点,但既然你说你只会做1次,也许就没有必要进一步优化了。

(pcode)
create table values ( id int auto_increment, value1 int, value2 int value3 int, 
    primary key(id), unique key( value1, value2, value3 ));    
foreach( $array as $val )
{
   $q = $pdo->prepare( "insert ignore into values ( value1, value2, value3 ) values (?,?,?) " )
   $q->bindParam( $val->value1 );
   ...
}

然后进行第二次传递,从values中选择适当的值并插入到关系表中。

(pcode)
foreach( $array as $val )
{
   $ret = $pdo->do( "select id from values where value1 = ?, value2 = ?, value3 = ?" );
   ( build the query )
   $row = $ret->fetch();
   $id = $row->id;
   (now insert into relations )
   $pdo->prepare( "insert into relations (usr_id, values_id ) values ( ?, ? )" );
   $pdo->bindParam( 1, $id );
   $pdo->bindParam( 2, $val->usr_id );
   $pdo->execute();
}