我有这段代码用于迭代数组playerForm
。无法遍历此字典并将其组织成自定义结构
playerForm
包含阵列中每个玩家的数组数量,并包含每个玩家的表单。
即
["playerForm": {
1 = (
{
date = "2017-01-31";
name = Dicky;
result = L;
"results_id" = 42;
},
{
date = "2017-01-26";
name = Dicky;
result = L;
"results_id" = 41;
}
);
2 = (
{
date = "2017-01-25";
name = G;
result = W;
"results_id" = 38;
},
{
date = "2017-01-25";
name = G;
result = D;
"results_id" = 40;
}
3 = (
{
date = "2017-01-31";
name = Sultan;
result = W;
"results_id" = 42;
},
{
date = "2017-01-26";
name = Sultan;
result = W;
"results_id" = 41;
}
);
}]
这是我想使用的代码:
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
print (json!)
if let dict = json?["playerForm"] as? [String:Any] {
print ("step 1")
for value in dict {
if let arr = value as? [[String:Any]] {
print(arr)
self.leagueForm = arr.flatMap { Form($0) }
for form in self.leagueForm {
self.formGuide.append(form.player_result!)
}
print ("break")
}
}
print (self.formGuide)
}
这是我自定义的结构来组织数据;
struct Form {
var player_result: String?
var player_name: String?
var result_date: String?
var result_id: String?
init(_ dictionary: [String : Any]) {
self.player_result = dictionary["result"] as? String ?? ""
self.player_name = dictionary["name"] as? String ?? ""
result_date = dictionary["date"] as? String ?? ""
result_id = String(dictionary["results_id"] as? Int ?? 0)
}
}
var leagueForm = [Form]()
但是,我收到警告:Cast from '(key: String, value: AnyObject)' to unrelated type [[String : Any]] always fails
。
这是我的PHP脚本提供初始阵列:
$noPlayers = count($communityPlayersIds); //
$playerForm = array();
$playerForm = $dao->getCommunityForm($communityId, $noPlayers, $communityPlayersIds);
public function getCommunityForm($communityId, $noPlayers, $communityPlayersIds){
$sql = " SELECT IF(player1_id=?, player1_result, player2_result) AS result, IF(player1_id=?, player1_name, player2_name) AS name, date, results_id FROM `results` WHERE (player1_id=? OR player2_id=?) AND community_id=? ORDER BY date DESC Limit 8";
$stmt = $this->conn->prepare($sql);
$i = 0;
foreach ($communityPlayersIds as $cPI) {
$i++;
$stmt->bind_param("iiiii", $cPI, $cPI, $cPI, $cPI, $communityId);
$stmt->execute();
if ($result = $stmt->get_result()) {
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$returnValue[$i][] = $row;
}
}
}return $returnValue;
}
echo json_encode (array('playerForm' => $playerForm));
所以这个1,2,3在上面的例子是我怎么也收录从MySQL返回的结果。我这样做是为了分离数据,这样我就可以在Swift中构建它了。
我在哪里出错了?
您可以显示JSON通过SWIFT而不是PHP打印出来? – johnslay
Hi @johnslay是通过Swift打印的JSON ... – RDowns
确定,并且正在打印出'第1步',还是无法投射并输入范围以打印出来? – johnslay