我正在尝试从API提取数据并将其插入MySQL表中。 在此过程中,我正在使用for-each循环来获取数据数组。如何避免多次使用循环而只在一个循环中使用索引?
<?php
$db = mysqli_connect('localhost', 'root', '', 'testing');
$url = 'MYAPI';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "",
CURLOPT_HTTPHEADER => array(
"accept: application/json",
"cache-control: no-cache",
"content-type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err)
{
echo "cURL Error #:" . $err;
}
else
{
$source = json_decode($response);
if (is_array($source) || is_object($source))
{
foreach( $source->DATA as &$data )
{
$data = array_combine( $source->COLUMNS, $data );
}
$CLIENTCODE = ( array_column( $source->DATA, 'CLIENTCODE') );
$BRANCHCODE = ( array_column( $source->DATA, 'BRANCHCODE') );
$FAMILYCODE = ( array_column( $source->DATA, 'FAMILYCODE') );
$CLIENTNAME = ( array_column( $source->DATA, 'CLIENTNAME') );
$BRANCHNAME = ( array_column( $source->DATA, 'BRANCHNAME') );
foreach ($CLIENTCODE as $cc)
{
$query = "INSERT INTO holding (CLIENTCODE) VALUES('$cc')";
mysqli_query($db, $query);
}
foreach ($BRANCHCODE as $bc)
{
$query = "INSERT INTO holding (BRANCHCODE) VALUES('$bc')";
mysqli_query($db, $query);
}
.
.
.
.
.
}
}
?>
答案 0 :(得分:2)
您可以在单个mysql查询中添加多个值,将所有数据作为如下所示的值放置,然后执行一次数据库插入查询
查询语法
:chk='Y' and closdt is null
OR
:chk is null
OR
:chk != 'Y'
示例
INSERT INTO MyTable ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )