我有这个多维数组:
array(88) {
[0]=>
array(9) {
["currency_pair"]=>
string(6) "BTCCAD"
["type"]=>
string(3) "Buy"
["trade_id"]=>
string(5) "34637"
["order_id"]=>
string(8) "51214063"
["quantity"]=>
string(10) "0.03296178"
["price"]=>
string(6) "271.83"
["total"]=>
string(4) "8.96"
["fee"]=>
string(4) "0.04"
["executed"]=>
string(19) "2015-06-05 03:04:21"
}
[1]=>
array(9) {
["currency_pair"]=>
string(6) "BTCCAD"
["type"]=>
string(3) "Buy"
["trade_id"]=>
string(5) "34631"
["order_id"]=>
string(8) "51183954"
["quantity"]=>
string(10) "0.47688340"
["price"]=>
string(6) "271.45"
["total"]=>
string(6) "129.45"
["fee"]=>
string(4) "0.54"
["executed"]=>
string(19) "2015-06-04 23:19:09"
}
[2]=>
array(9) {
["currency_pair"]=>
string(6) "BTCCAD"
["type"]=>
string(3) "Buy"
["trade_id"]=>
string(5) "34630"
["order_id"]=>
string(8) "51169904"
["quantity"]=>
string(10) "0.25000000"
["price"]=>
string(6) "272.63"
["total"]=>
string(5) "68.16"
["fee"]=>
string(4) "0.29"
["executed"]=>
string(19) "2015-06-04 21:45:01"
}
}

我想迭代数组,获取每个键的值(例如," currency_pair"," type"," trade_id"等)和将它们插入mysql表。
foreach ($datas as $data) {
$datetime = $data['executed'];
$currency_pair = $data['currency_pair'];
$type = $data['type'];
$quantity = $data['quantity'];
$rate = $data['price'];
$total = $data['total'];
$fee = $data['fee'];
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "myDB";
$connection = mysqli_connect($servername, $username, $password, $dbname);
// create connection
if (!$connection) {
die("connection failed: " . mysqli_connect_error());
} else {
echo "connected! ";
}
// sql to create table
$sql = "INSERT INTO Transactions (type)
VALUES ('$type')";
if (mysqli_query($connnection, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($connnection);
}
}
mysqli_close($connection);
&#13;
我只想插入&#39;类型&#39;在上面的例子中进入数据库。我收到两个错误:
1)PHP注意:未定义的变量:
中的连接2)PHP警告:mysqli_error()期望参数1为mysqli,给定为null
答案 0 :(得分:0)
首先,您的JSON无效,上部大括号应为方括号。
应该是:
[
{
"date" : "May 12",
"id" : "20",
"type" : "tall"
},
{
"date" : "May 14",
"id" : "30",
"type" : "short"
},
{
"date" : "May 17",
"id" : "70",
"type" : "giant"
}
]
您可以使您的JSON源正确或删除您的响应的第一个和最后一个字符,并用方括号括起来,如:
$json_response = '['.substr(trim($response), 1, -1).']';
在执行json_decode
并循环
$json_array = json_decode($json_response);
if(!empty(json_response)){
foreach ($json_response as $key => $value) {
// Do Something!
}
}