-1

目前正在与朋友一起编写服务脚本。当我说服务脚本时,我的意思是它只会用于更新和向数据库添加值。现在我的朋友已经将她所有的值存储为数组作为数据库的值。

我已经成功地输入了其中一个数组,现在我对如何为多个数组执行此操作感到困惑。所以总而言之,这更像是一个关于如何重构我当前的代码以使其更具动态性的问题。

还请记住,她有数百个数组需要这样做,所以它不像 2 或 3,它实际上是数百个。

我更新的代码:(请阅读评论)

$colors['Colors_All'] = array("Black","Charcoal"); // Add unique indexes
$colors['Colors_Bright_All'] = array("Silver","White"); // Add unique indexes

$AllArrays = get_defined_vars(); // Get all defined vars
$Arrays = array(); // Set a default array

foreach ($AllArrays as $varName => $value) { // Run through all the variables set in AllArrays
        if(is_array($value) && $varName == 'colors') { // If array is colors then
                $Arrays = array_merge($Arrays, $value); // Merge those arrays into the new array
        }
}

var_dump($Arrays);

$sql = "INSERT INTO `product_features` ("; // Create the initial query

foreach ($Arrays as $column => $value) { // ForEach over the array
        $sql .= "$column,"; // Use the Key Example : 'Colors_All and Color_Bright_All' as a column name
}

$sql2 = rtrim($sql, ","); // trim the initial "," from the columns at the end
$sql2 .= ")"; // Close off the columns names
$sql2 .= " VALUES ";

foreach ($Arrays as $column => $value) { // This is where the problem starts -_-
        foreach ($value as $key => $insert) { // Get the value
                $sql2 .= "('$insert', '$insert'),"; // I need to have unique values here :(
        }
}

$finSQL = rtrim($sql2, ","); // Strip off the remaining ","

我也知道不是绑定参数,一旦我得到了真正的硬东西,我会的。

现在,在转储 $finSQL 时,我得到了这个:

string(152) "INSERT INTO `product_features` (Colors_All,Colors_Bright_All) VALUES ('Black', 'Black'),('Charcoal', 'Charcoal'),('Silver', 'Silver'),('White', 'White')"

如何让唯一值成为插入查询中的 VALUES?这是让我感到困惑的最后一部分。

4

6 回答 6

1

将 $Colors_Bright_All, $Colors_Light_All 放入一个最终数组中,假设 $finalArray 并使用 foreach 循环遍历该数组,然后在其中执行现有的 foreach 循环。

于 2013-04-20T05:02:36.077 回答
0

作为上述问题的解决方案,请尝试执行以下代码片段

例如

    $finalarray=array();

    $Colors_Bright_All =    array("Silver","White","Gold","Royal_Blue","Dodger_Blue","Deep_Sky_Blue","Deep_Green","Forest_Green","Bright_Green","Violet"); 

   $Colors_Light_All = array("Light_Gray","Silver","White","Gold","Dodger_Blue","Deep_Sky_Blue","Light_Blue","Bright_Green","LightGreen","Light_Green");

 array_push($finalarray,'('.join(',',$Colors_Bright_All).')');
 array_push($finalarray,'('.join(',',$Colors_Light_All).')');

  $value=join(',',$finalarray);

 $sql = "INSERT INTO `product_features` (Colors_All) VALUES ".$value; // Build the initial query 
 $finSQL = rtrim($sql, ","); // Strip the last , so our mysql query doesn't goof up. 
 $stmt = $conn->prepare($finSQL);
 $stmt->execute();
于 2013-04-20T05:31:25.400 回答
0

正如您已经在其他答案中被告知的那样,制作嵌套数组是唯一明智的方法

$colors['bright'] = array("Silver","White","Gold"...); 
$colors['light']  = array("Light_Gray","Silver","White"...);

foreach ($colors as $type => $array) {

     // put your code here

}

如果您需要更多数据来插入$type(因为它不能从您极其模糊的问题中得知),您也可以添加一个包含这些数据的数组

于 2013-04-20T05:34:27.077 回答
0

好吧,我通过序列化每个数组并使用实际数组索引作为数据库中的唯一标识符来“完成”,如下所示:

<?php
ini_set("error_reporting", E_ALL);
ini_set("display_errors", TRUE);

$conn = new MysqlI("HOST", "USER", "PASSWORD", "DATABASE" /*Optionally put the PORT NUMBER HERE : , 3306 */);    
$conn->set_charset('utf8'); // Always explicitly state the character encoding!

$clearSQL = "TRUNCATE TABLE `product_features`;";
$clearNOW = $conn->prepare($clearSQL);// For updating this will delete all records in the table
$clearNOW->execute();

$colors['Colors_All'] = array("Black", "Charcoal", "Pink", "Cheese", "Dog", "Punk"); // Add unique indexes
$colors['Colors_Bright'] = array("Silver", "White", "Yellow", "Blue", "Indigo"); // Add unique indexes
$colors['Colors_Bright_All'] = array("Silver", "White", "DarkYellow", "Dark_Pink",); // Add unique indexes
$colors['Colors_Dark'] = array("Silver", "White", "DarkWE", "DarkCheese", "DarkBla"); // Add unique indexes
$colors['Colors'] = array("Silver", "White", "DarkIDK", "DarKsome", "waDark", "dark"); // Add unique indexes
$colors['Colors_Green'] = array("Silver", "White", "WAA", "WIWIW", "OMG", "Blood"); // Add unique indexes
$colors['Colors_Red'] = array("Silver", "White", "IRI", "owow", "Darkness", "night"); // Add unique indexes

$AllArrays = get_defined_vars(); // Get all defined vars
$Arrays = array(); // Set a default array

foreach ($AllArrays as $varName => $value) { // Run through all the variables set in AllArrays
    if (is_array($value) && $varName == 'colors') { // If array is colors then
       $Arrays = array_merge($Arrays, $value); // Merge those arrays into the new array
    }
}

$sql = "INSERT INTO `product_features` (`ArrayIndex`, `ArrayValues`) VALUES "; // Create the initial query

foreach ($Arrays as $ArrayIndex => $Arrayvalues) { // ForEach over the array
     $sql .= "('$ArrayIndex','" . $mysqli->mysqli_real_escape_string(serialize($Arrayvalues)) . "'),"; // Use Array Index as the Unique Array Identifyer and Arrayvalues for the value
}

$finSQL = rtrim($sql, ","); // Strip off the remaining ","

var_dump($finSQL); // Check the query

$INSERT = $conn->prepare($finSQL); // Get query ready
$INSERT->execute(); // Execute

?>

数据库中的结果是这样的

于 2013-04-24T12:07:30.867 回答
0

如果您的代码工作正常,则更改

foreach ($Arrays as $column => $value) { // This is where the problem starts -_-
        foreach ($value as $key => $insert) { // Get the value
                $sql2 .= "('$insert', '$insert'),"; // I need to have unique values here :(
        }
}

foreach ($Arrays as $column => $value) { // The problem will be fixed :D
        $sql2 .="(";
        foreach ($value as $key => $insert) { // Get the value
                $sql2 .= "'$insert',"; // You will have unique values here :D
        }
        $sql2 = chop($sql2,","); // strip the ending ,
        $sql2 .= "),";
}
于 2013-06-15T01:33:56.430 回答
-1
<?php
function myInsert($myArray)
{
    $colour_value = "";
    $stmt = $mysqli->prepare("INSERT INTO `product_features` (Colors_All) VALUES (?)");

    if ($stmt) {
        $stmt->bind_param("s", $colour_value );


        foreach ($myArrayas AS $value) {
            $colour_value = $value;
            $stmt->execute();
        }

        $stmt->close();
    }
}


function myInsert($Colors_Bright_All);
function myInsert($Colors_Light_All);
?>

编辑

<?php
$newArray = array();

foreach( $_GLOBALS as $val )
{
    if( substr($val, 0, 7) == "Colors_" )
        myInsert($val);
}

?>
于 2013-04-20T05:25:42.203 回答