0

我一直试图找到这个问题的答案一段时间,但我无法......所以我不得不问一个问题......

简而言之,我不会发布任何我拥有的代码,而是直接提出问题。

我有看起来像这样的数组:

Array
(
    [0] => Array
        (
            [0] => ID09666
            [1] => ID14366
            [2] => ID8174
            [3] => ID4106
        )

    [1] => Array
        (
            [0] => /title_is_fantastic/
            [1] => /what_an_awesome_title/
            [2] => /great_title/
            [3] => /awesome_title/
        )

    [2] => Array
        (
            [0] => Title is fantastic
            [1] => What an awesome title
            [2] => Great title
            [3] => Awesome title
        )

    [4] => Array
        (
            [0] => 100%
            [1] => 86%
            [2] => 76%
            [3] => 68%
        )

)

我需要添加到数据库的值是:

ID = ID09666
url = /title_is_fantastic/
title = Title is fantastic
percent = 100%

那么如何才能最快地将这些值添加到数据库中呢?我对这个数组感到非常困惑,因此感谢您的帮助。

谢谢!

4

2 回答 2

0

假设您的数组是$array

$length = count($array[0]);
$rows = array();
for($i = 0; $i < $length; $i++)
     $rows[] = "(".array($array[0][$i].", ".$array[1][$i].", ".$array[2][$i].", ".$array[3][$i].")";

// Ugly language with no executemany function... So we build a INSERT INTO with many values by ourselves 
$sql = "INSERT INTO table (id, url, title, percent) VALUES " . implode(',', $rows);

$stmt = $pdo->prepare ($sql);
try {
    $stmt->execute($insert_values);
} catch (PDOException $e){
    echo $e->getMessage();
}
$pdo->commit();
于 2013-08-25T11:07:05.050 回答
0

嗯,我想我明白你的意思了。问题是你的原始数组有点奖励。如果我是你,我会创建一个函数来首先将数组重新排列为以下形式:

Array
(
    [0] => Array
        (
            [id] => ID09666
            [url] => /title_is_fantastic/
            [title] => Title is fantastic
            [percent] => 100%
        )
     ...
)

然后直接访问第一个(或任何)元素。该功能类似于:

function rearrange($arr){
    $array_number = count($arr[0]);
    $new_arr = array();
    for ($i=0,$i<$array_number<$i++){
       $new_arr[$i]['id']=$arr[0][$i];
       $new_arr[$i]['url']=$arr[1][$i];
       $new_arr[$i]['title']=$arr[2][$i];
       $new_arr[$i]['percent']=$arr[3][$i];
    }
    return $new_arr;
}
于 2013-08-25T11:24:43.647 回答