0

我有一个数组,它有 10 多个索引。

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

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

它会插入

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

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

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

我怎么能做到这一点?

4

3 回答 3

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) 
        {
}
于 2013-09-03T19:55:22.933 回答
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 ;
}
于 2013-09-03T18:58:12.387 回答
0

基本上是将数组拆分为子数组,对吗?如果是这样,那么看看array_chunk()

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

于 2013-09-03T19:19:58.500 回答