遍历复杂关联数组时,如何实现数据库单次插入?
问题:遍历关联数组插入数据库时出现13条重复记录
我正在使用如下复杂关联数组:
Array ( [device_id] => 432552343242 [host_name] => computer [serial_number] => 32525243 [manufacturer] => HP [model] => ProLiant BL460c Gen9 [locations] => Array ( [0] => Array ( [name] => New York ) ) [cpu_count] => 1 [core_count] => 6 [is_virtual] => [operating_system] => Array ( [version] => 6.6 Santiago [product] => Array ( [vendor] => Varied [description] => ProductAdapter for handling various Unix or Linux based Operating Systems (HP-UX, AIX, Solaris, Ubuntu, etc...) [name] => Unix Operating Systems ) [name] => Linux Server ) [users] => mydomain.com/users [applications] => mydomain.com/applications [qualified_name] => Array ( [0] => Array ( [name_type] => UnixName [name] => cbc.com ) [1] => Array ( [name_type] => DNSFQDN [name] => abc.com ) [2] => Array ( [name_type] => DNSDomain [name] => bbc.com ) [3] => Array ( [name_type] => OriginalHostname [name] => cnn.com ) ) )
当我尝试遍历该数组并插入数据库时,得到了13条记录。我的代码如下:
$array = json_decode($result, true); foreach($array as $key=>$value) { $hostname = $array['locations']; $stmt = $mysqli->prepare("INSERT INTO test (Hostname) VALUES (?)"); $stmt->bind_param("s", $hostname); $stmt->execute(); $stmt->close(); }
我知道原因是循环遍历数组的每个索引,每次都插入hostname,导致重复插入。请问如何实现仅插入一次?是否需要使用for语句或嵌套foreach?作为新手,恳请帮助。
解决方案
嘿,别担心,这个问题其实很容易解决!
首先咱们明确问题根源:你的foreach($array as $key=>$value)是在遍历整个大数组的所有13个键值对(数一下数组里的元素:device_id、host_name、serial_number...一共13个),所以循环会执行13次,每次都执行一遍插入操作,自然就得到了13条重复记录。
你根本不需要遍历整个数组来插入这一条数据!直接取出你需要的字段值,执行一次插入就好。另外还要注意:$array['locations']本身是一个数组,你需要的是里面的name值(也就是New York),直接绑定数组会有问题,得把具体值取出来。
修正后的代码如下:
$array = json_decode($result, true); // 取出locations里的具体名称 $hostname = $array['locations'][0]['name']; // 只执行一次插入操作 $stmt = $mysqli->prepare("INSERT INTO test (Hostname) VALUES (?)"); $stmt->bind_param("s", $hostname); $stmt->execute(); $stmt->close();
这样就只会插入一条记录啦!
如果之后你有批量插入多条数据的需求(比如遍历qualified_name里的多个名称插入),那时候才需要用到循环,但现在只需要插入单个值,完全不需要循环整个大数组~
内容的提问来源于stack exchange,提问作者biggambino
相关产品推荐
相关产品推荐

