根据数组索引将一个数组插入2个表中

时间:2013-09-03 18:45:53

标签: php arrays

我有一个数组,它有10个以上的索引。

我想要做的是根据索引设置变量$ table,以便插入

Array[0] - Array[9] to $table = table1

它会插入

Array[10] - Array[14] to $table = table2

我不想使用if语句,因为我需要它们都插入

我希望将这一切保留在一个查询中并使用$ table(如果可能的话)

我怎么能实现这个目标?

3 个答案:

答案 0 :(得分:1)

$table = array();

foreach($array as $key => $value)
  if ($key <= 9)
    $table['table1'][$key] = $value;
  else
    $table['table2'][$key] = $value;

这将把它作为一个数组保存。我认为这是你想要的。

我对SQL查询很糟糕,所以如果每个键都是表中的一列,那么下面只是伪的:

foreach($table as $key => $value){
    if($key == 'table1'){
        foreach($value as $key => $value){
            //INSERT INTO table1 ($key) VALUES ($value) 
        {
    if($key == 'table2'){
        foreach($value as $key => $value){
            //INSERT INTO table2 ($key) VALUES ($value) 
        {
}

答案 1 :(得分:0)

所以你创建了2个数组并使用它们:

$table1 = array() ;  //Save data into arrays so you can put it in a database (?)
$table2 = array() ;

foreach(array_values($array) as $key => $value){
  if ($key <= 9)
    $table1[] = $value ;
  else
    $table2[] = $value ;
}

答案 2 :(得分:0)

基本上是将数组拆分成子数组,对吧?如果是,请查看array_chunk()

http://php.net/manual/en/function.array-chunk.php