将多维php数组插入mysql表

时间:2017-02-14 18:03:24

标签: php mysql arrays multidimensional-array

这是我拥有的多维数组。我是新来的Php ..我想输入名称,文件夹和上传到sql表但是我被困在数组部分。我需要帮助

Array
(
[status] => 200
[msg] => OK
[result] => Array
    (
        [folders] => Array
            (
                [0] => Array
                    (
                        [id] => 1861013
                        [name] => .videothumb
                    )

            )

        [files] => Array
            (
                [0] => Array
                    (
                        [name] => wildlife.mp4
                        [cblock] => 
                        [sha1] => d5d4e1001f98f70324ef4f84ccd6d683f653c513
                        [folderid] => 1861011
                        [upload_at] => 1487016733
                        [status] => active
                        [size] => 558253404
                        [link] => link here
                        [download_count] => 0
                        [cstatus] => ok

                    )

            )

    )

)

这里是我试图用来将数据插入表中的mysql插入代码,但我在数据库中得到的只是零

 $st = $dbh->prepare("INSERT INTO movies(name, upload_at, link, folderid)     
  VALUES (:field1, :field2, :field3, :field4)");


 // bind variables to insert query params

      $st->bindParam(1, $name);
      $st->bindParam(2, $uploadat );
      $st->bindParam(3, $link);
      $st->bindParam(4, $folderid);




  $json = file_get_contents($filename);   

//convert json object to php associative array

$data = json_decode($json, true);





// loop through the array
foreach ($data as $item) 
 {  $name = $item['result']['folders'][0]['id'];
  $uploadat = $item['result']['files'][0]['upload_at']; 
  $link = $item['result']['files'][0]['link']; 
  $folderid = $item['result']['files'][0]['folderid'];   

    echo $name;
    echo $folderid;
    // execute insert query
    $st->execute(array(':field1'=>$name,
                       ':field2'=>$uploadat,
                       ':field3'=>$link,
                       ':field4'=>$folderid));
}

1 个答案:

答案 0 :(得分:0)

因为数组结构没有将文件子数组嵌套在文件夹子数组中,所以我假设文件夹'索引对应文件'指数。

foreach($data["result"]["folders"] as $index=>$subarray){
    $st->execute(array(':field1'=>$subarray["id"],
                       ':field2'=>$data["result"]["files"][$index]["uploadat"],
                       ':field3'=>$data["result"]["files"][$index]["link"],
                       ':field4'=>$data["result"]["files"][$index]["folderid"]));
}

可疑,$data["result"]["files"][$index]["folderid"]与您的示例数组中的$subarray["id"]不匹配。

如果需要array_search() folderid,则需要修改此代码段。