Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

php多维数组入库的问题

Array
(

[name] => Array
    (
        [0] => 打豆豆
        [1] => 111
        [2] => 222
    )

[jine] => Array
    (
        [0] => 111
        [1] => 111
        [2] => 22
    )

[renshu] => Array
    (
        [0] => 11
        [1] => 11
        [2] => 222
    )

)

这样的数组怎么入库 php mysql
name 是一个字段 jine是一个字段 有多少个序号就插入多少条数据 分别对应name jine renshu


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
<?php
$arr = [
'name'   =>
    [
        '打豆豆',111,111
    ],
'jine'   => [
        '111','111','111'
    ],
'renshu' => [
        11,111,11
    ]
];
// 整理数组
$settle_array = [];
$count = count($arr);
$i     = 0;

while ( $i < $count) {
    $settle_array[] = [
        'name' =>  $arr['name'][$i],
        'jine' =>  $arr['jine'][$i],
        'renshu' =>  $arr['renshu'][$i],
    ];
    ++$i;
}
// 数据入库
insertMore($settle_array);
function insertMore(array $param)
{
    $keys    = [];
    $values  = [];
    $fill    = '';
    $data    = [];
    foreach ($param as $param_key => $param_val) {
        foreach($param_val as $child_key => $child_val){
                array_push($values,$child_val);
        }
        if( is_array($param_val)){
            $fill.= '('.implode(',', array_fill(0, count($param_val), '?')).'),';
        }
    }

    $sql  = 'INSERT INTO `'.$this->table.'` ('.implode(',', array_keys($param[0])).') VALUES '.trim($fill,',');
    $stmt = $this->pdo->prepare($sql);

    $stmt->execute($values);
    $this->errorInfo = $stmt->errorInfo();
    return $this->getLastInsertId();
} 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...