我正在使用一个以 json 格式返回搜索结果的 API。然后,我需要将其写入 MYSQL 表。我之前已经成功地做到了这一点,但这次情况有所不同,我认为这是因为结果数组的结构:键名是动态的,如果特定键不存在数据,则键不存在列在数组中。这是数组的示例 vardump:
array
0 =>
array
'title' => string 'Funny but not funny' (length=19)
'body' => string 'by Daniel Doi-yesterday while eating at Curry House...
'url' => string 'http://danieldoi.com/2012/11/20/funny-but-not-funny/'
'source_site_name' => string 'WordPress.com' (length=13)
'source_site_url' => string 'http://www.wordpress.com' (length=24)
'query_topic' => string 'thanksgiving' (length=12)
'query_string' => string 'blogs=on&topic=thanksgiving&output=json' (length=39)
1 =>
array
'title' => string 'Travel Easy this Holiday Season...' (length=34)
'body' => string 'Give yourself a few gifts and get this holiday season off...
'url' => string 'http://facadebeauty.wordpress.com/2012/11/20
'date_published' => string 'Tue, 20 Nov 2012 18:22:35 +0000' (length=31)
'date_published_stamp' => string '1353435755' (length=10)
请注意键的顺序/包含如何更改。
我提出的解决方案是使用数组键作为列名,将它们变成一个变量以在查询语句中使用,但这对我不起作用。这是我的尝试:
$jsonString = file_get_contents("http://search-query-URL&output=json");
$array = json_decode($jsonString, true);
// database connection code snipped out here
$table = "results";
foreach($array as $arr_value) {
foreach ($arr_value as $value) {
$colName = key($arr_value);
$colValue = ($value);
$insert="INSERT INTO $table ($colName) VALUES ('$colValue')";
mysql_query($insert) OR die(mysql_error());
next($arr_value);
}
}
关于下一步看哪里的任何建议?谢谢!
更新 11/27:
在这里,我试图适应大卫的建议。我收到以下错误:“数据库连接错误 (1110) 列 'title' 在查询中指定了两次。”
这是我现在的代码:
$mysqli = mysqli_connect("localhost");
mysqli_select_db($mysqli, "mydatabase");
foreach ($array as $column) {
foreach ($column as $key => $value) {
$cols[] = $key;
$vals[] = mysqli_real_escape_string($mysqli, $value);
}
}
$colnames = "`".implode("`, `", $cols)."`";
$colvals = "'".implode("', '", $vals)."'";
$mysql = mysqli_query($mysqli, "INSERT INTO $table ($colnames) VALUES ($colvals)") or die('Database Connection Error ('.mysqli_errno($mysqli).') '.mysqli_error($mysqli). " on query: INSERT INTO $table ($colnames) VALUES ($colvals)");
mysqli_close($mysqli);
if ($mysql)
return TRUE;
else return FALSE;
最后更新 - 工作!
它正在工作。这是我们所拥有的:
$mysqli = mysqli_connect("localhost");
mysqli_select_db($mysqli, "mydatabase");
foreach ($array as $column) {
foreach ($column as $key => $value) {
$cols[] = $key;
$vals[] = mysqli_real_escape_string($mysqli, $value);
}
$colnames = "`".implode("`, `", $cols)."`";
$colvals = "'".implode("', '", $vals)."'";
$mysql = mysqli_query($mysqli, "INSERT INTO $table ($colnames) VALUES ($colvals)") or die('Database Connection Error ('.mysqli_errno($mysqli).') '.mysqli_error($mysqli). " on query: INSERT INTO $table ($colnames) VALUES ($colvals)");
unset($cols, $vals);
}
mysqli_close($mysqli);
if ($mysql)
return TRUE;
else return FALSE;