将多维php数组插入mysql数据库 [英] Inserting a multi-dimensional php array into a mysql database

查看:93
本文介绍了将多维php数组插入mysql数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自csv的数组,其结构与此类似:

I have an array from a csv with a similar structure to this:

Array (
    [0] => Array ( [0] => name [1] => age [2] => gender )
    [1] => Array ( [0] => Ian [1] => 24 [2] => male )
    [2] => Array ( [0] => Janice [1] => 21 [2] => female )
     etc

我想将其插入到mysql表中,其中第一个数组的项(名称,年龄,性别)是列标题,而每个后续数组是表中的一行.

I would like to insert insert it into a mysql table where the items of the first array (name, age, gender) are the column titles and each subsequent array is a row in the table.

有人会建议我这样做的最好方法吗,因为我撞墙了,这让我头疼!

Could anyone advise as to the best way to do this as I have hit a wall and it has left me with a hurting head!

推荐答案

以下代码将起作用,但是它假定所有嵌套数组的长度都相同,换句话说,每个嵌套数组都包含所有属性的值在第一个嵌套数组中定义.

The following code will work, but it assumes that the length of all nested arrays is the same, in other words that each nested array contains values for all the attributes defined in the first nested array.

$array = array(
    array('name', 'age', 'gender' ),
    array('Ian', 24, 'male'),
    array('Janice', 21, 'female')
);

$fields = implode(', ', array_shift($array));

$values = array();
foreach ($array as $rowValues) {
    foreach ($rowValues as $key => $rowValue) {
         $rowValues[$key] = mysql_real_escape_string($rowValues[$key]);
    }

    $values[] = "(" . implode(', ', $rowValues) . ")";
}

$query = "INSERT INTO table_name ($fields) VALUES (" . implode (', ', $values) . ")";

只要所有其他嵌套数组的长度相同,此解决方案就可以与第一个嵌套数组中定义的任意数量的属性一起使用.对于上方的数组,输出为:

This solution will work with any number of attributes defined in the first nested array, as long as all other nested arrays have the same length. For the array above the output will be:

INSERT INTO table_name (name, age, gender) VALUES (Ian, 24, male), (Janice, 21, female)

有关演示,请参见 http://codepad.org/7SG7lHaH ,但请注意,我删除了通话到codepad.org上的mysql_real_escape_string(),因为它们不允许使用该函数.在您自己的代码中,您应该使用它.

For a demonstration see http://codepad.org/7SG7lHaH, but note that I removed the call to mysql_real_escape_string() on codepad.org, because they do not allow the function. In your own code you should use it.

这篇关于将多维php数组插入mysql数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆