[英]Passing NSMutableArray to PHP through POST
我试图在一个帖子中包含一个数组到PHP Web服务。 它似乎没有工作,我相信它必须是某种格式化问题,但我不知道如何格式化它。 我有以下iOS帖子字符串:(我知道怎么POST,这不是问题。)
NSString *post = [NSString stringWithFormat:@"&action=post_data&start_time=%f&runners=%@&racename=%@&num_splits=%d", timeInterval, runners /* NSMutableArray */, raceName, numberOfSplits];
“runners”是NSMutableArray,只是以这种方式传递它似乎无法正常工作。
我应该如何传递数组? 我无法更改PHP,并且服务期望数组。 我会将JSON对象传递给服务,但这是我无法控制的。
PHP就是以下内容:
$runners = $_POST["runners"];
我不清楚PHP想要在该参数中得到什么。
如果PHP希望在$runners
找到一个数组,那么你需要发送一个带有这个内容的POST查询(至少):
runners[]=element1&runners[]=element2&...
这将由PHP翻译成一个数组
{ 'element1', 'element2', ... }
如果您发送了
runners[key1]=element1&runners[key2]=element2&...
然后你会用PHP获得与你写的相同的结果
$runners = array(
'key1' => 'element1',
'key2' => 'element2',
...
);
JSON与它无关, 除非PHP在$runners
上执行json_decode
。 (你没有说过这种情况,所以我认为不是这样)。
伊塞米是对的。 要将数组作为post变量传递,您需要使用以下格式创建url字符串:
http://myserver.com/test.php?myArray[]=123&myArray[]=456
这是我实现它的方式:
NSArray *arrayWithIDs = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:123], [NSNumber numberWithInt:456], nil];
NSString *postVarArrayString = @"";
NSString *separator = @"?";
for (int i=0; i<[arrayWithIDs count]; i++) {
if (i>0) {
separator = @"&";
}
postVarArrayString = [NSString stringWithFormat:@"%@%@myArray[]=%d", postVarArrayString, separator, [[arrayWithIDs objectAtIndex:i] integerValue]];
}
// url
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:
@"http://myserver.com/test.php"
@"%@"
, postVarArrayString]
];
NSLog(@"%@", [url absoluteString]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.