能不能访问JSON数组在PHP中,它返回null和警告:提供的foreach无效参数() [英] Cannot able to access json array in php , it returns null and Warning: Invalid argument supplied for foreach()
问题描述
我试图JSON数组中发送到PHP和插入多行表
问题:
PHP的:
- 无法访问德code JSON数组 - 数组count返回零
- 警告:提供的foreach无效参数()
当我打印的JSON字符串它给了我下面的数据
[
{
电子邮件:,
名称:DDD
contact2:,
ontact1:
},
{
电子邮件:,
名称:DDD
contact2:,
contact1:
},
{
电子邮件:,
名称:Dddddr
contact2:,
contact1:
}
]
但是,当我试图访问使用PHP,显示了我的错误
PHP code:
< PHP $ inputJSON =的file_get_contents('PHP://输入');
$阵列= json_de code($ inputJSON,真正的); 回声计数($数组); 的foreach($数组作为$项目){
$用途= $项目['名称'];
回声$使用;
}?>
错误:
警告:提供的foreach无效参数()
块引用>所以,我测试了使用数组在PHP,
IsArray的()||则IsObject funtion但它打印空
COUNT()funcions提供0 后续代码var_dump($数组);结果NULL但我去code数组,并检查结果在iOS中,它给数组作为响应。
回声json_en code($数组);
但是在PHP我不能够访问阵列。
不知道是否有在iOS的code的任何错误。在iOS中我有
的NSMutableDictionary
存储到的NSMutableArray
然后的NSArray
。
当我解析的NSMutableArray
我得到了同样的问题。的iOS code:
FUNC saveToCloud(){ VAR mutablearray = NSMutableArray的() VAR字典=的NSMutableDictionary() VAR eachRow = textfieldarry为[的UITextField]
对于eachField在eachRow {
让指数= eachRow.indexOf(eachField)
让数据= eachField.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
字典[键[指数!] =数据
} mutablearray.addObject(字典) VAR TonNSarray =的NSArray(数组:mutablearray)
VAR URL =myurl / file.php JsonParseTOSaveCloud(TonNSarray,urlstring:URL,successfullResponse:成功,alertmessage:非)
}保存到服务器:
FUNC ok_JsonParseTOSaveCloud(dict:AnyObject,urlstring:String,successfullResponse:String,alertmessage:String){ 让JSON:NSData的=试试! NSJSONSerialization.dataWithJSONObject(快译通,选择:NSJSONWritingOptions prettyPrinted)
变种D =的NSString(数据:JSON,编码:NSUTF8StringEncoding)
打印(jsonstr \\(D!))
让urlString = urlstring urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLPathAllowedCharacterSet())! 让HTT prequest = NSMutableURLRequest(网址:NSURL(字符串:urlString)) HTT prequest.HTTPMethod =POST HTT prequest.HTTPBody = JSON 让sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration() sessionConfig.HTTPAdditionalHeaders = [接受:应用/ JSON,API密钥:API_KEY] 让会话= NSURLSession(配置:sessionConfig) 让postDataTask = session.dataTaskWithRequest(HTT prequest,completionHandler:{(数据:NSData的?的回复:NSURLResponse?错误:NSError)在 如果数据== {为零 dispatch_async(dispatch_get_main_queue(),{ 让警报= UIAlertView中(标题:alertmessage,留言:你不再连接到Internet,委托:自我,cancelButtonTitle:辞退) alert.show() })
}其他{ 打印(数据\\(数据)) //让jsonResult =(试行NSJSONSerialization.JSONObjectWithData(数据!,选项:NSJSONReadingOptions.MutableContainers))
} }) postDataTask.resume()
}请注意:当我检查的PHP,这样它的作品。这时候,我给Jsonstring或jsonarray直接它的工作原理。
< PHP $ JSON ='[
{
电子邮件:,
名称:DDD
contact2:,
contact1:
},
{
电子邮件:,
名称:DDD
contact2:,
contact1:
},
{
电子邮件:,
名称:Dddddr
contact2:,
contact1:
}
]';$阵列= json_de code($ JSON,真正的);的foreach($数组作为$项目){
$用途= $项目['名称'];
回声$使用;
} ?>
解决方案在上帝恩典解决我的问题
在我原来的code中的错误是,我用每个所以data.First的访问给我warning.Then从链接
http://www.dyn-web.com /tutorials/php-js/json/de$c$c.php ,我得到了这样的访问,那么它的工作。$位置= $ DATA [0] [电子邮件];
然后我们使用数字和关联数组语法的组合来访问所需的元素多维数组。
I am trying to send json array to php and insert multiple rows in to table
Problem:
Php:
- Not able to access the decode JSON array - array count returns nil
- Warning: Invalid argument supplied for foreach()
When I print JSON string it gives me the below data
[ { "email" : "", "Name" : "Ddd", "contact2" : "", "ontact1" : "" }, { "email" : "", "Name" : "Ddd", "contact2" : "", "contact1" : "" }, { "email" : "", "Name" : "Dddddr", "contact2" : "", "contact1" : "" } ]
But when I am trying to access that using php that shows me a error
PHP CODE:
<?php $inputJSON = file_get_contents('php://input'); $array = json_decode($inputJSON, true); echo count($array); foreach($array as $item) { $uses = $item['Name']; echo $uses; } ?>
Error:
Warning: Invalid argument supplied for foreach()
So I tested the array in php using ,
Isarray() || Isobject funtion but it print null Count() funcions provide 0 var_dump($array); result NULL
But I decode the array and check the result in iOS, it gives the array as response
echo json_encode($array);
But in php I am not able access the array.
Not sure if there is any mistake in iOS code. In iOS I have
NSMutableDictionary
that is stored toNSMutableArray
and thenNSArray
. When I parse theNSMutableArray
I get the same problem.iOS code:
func saveToCloud(){ var mutablearray = NSMutableArray() var dict = NSMutableDictionary() var eachRow = textfieldarry as [UITextField] for eachField in eachRow { let index = eachRow.indexOf(eachField) let data = eachField.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) dict[keys[index!]] = data } mutablearray.addObject(dict) var TonNSarray = NSArray(array: mutablearray) var url = "myurl/file.php " JsonParseTOSaveCloud(TonNSarray, urlstring: url, successfullResponse: "Success", alertmessage: "not") }
Saving to Server:
func ok_JsonParseTOSaveCloud(dict:AnyObject,urlstring:String,successfullResponse:String,alertmessage:String){ let json:NSData = try! NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted) var d = NSString(data: json, encoding: NSUTF8StringEncoding) print("jsonstr\(d!)") let urlString = urlstring urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLPathAllowedCharacterSet())! let httpRequest = NSMutableURLRequest(URL: NSURL(string: urlString)!) httpRequest.HTTPMethod = "POST" httpRequest.HTTPBody = json let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration() sessionConfig.HTTPAdditionalHeaders = ["Accept" : "application/json", "api-key" : "API_KEY"] let session = NSURLSession(configuration: sessionConfig) let postDataTask = session.dataTaskWithRequest(httpRequest, completionHandler: {(data: NSData?, reponse: NSURLResponse?, error: NSError?) in if data == nil { dispatch_async(dispatch_get_main_queue(), { let alert = UIAlertView(title: alertmessage, message: "you are no longer connected to the Internet", delegate: self, cancelButtonTitle: "Dismiss") alert.show() }) } else { print("data\(data)") //let jsonResult = (try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) } }) postDataTask.resume() }
Note: When I check in php, like this it works. That is when I give the Jsonstring or jsonarray directly it works.
<?php $json = '[ { "email" : "", "Name" : "Ddd", "contact2" : "", "contact1" : "" }, { "email" : "", "Name" : "Ddd", "contact2" : "", "contact1" : "" }, { "email" : "", "Name" : "Dddddr", "contact2" : "", "contact1" : "" } ]'; $array = json_decode( $json, true ); foreach($array as $item) { $uses = $item['Name']; echo $uses; } ?>
解决方案With God Grace solved my problem The mistake in my original code was, the accessing of data.First i used for each so it gives me warning.Then from the link http://www.dyn-web.com/tutorials/php-js/json/decode.php, i got the accessing like this , then it worked.
$location = $data[0]['email'];
Then we use a combination of numeric and associative array syntax to access the desired element in multidimensional array.
这篇关于能不能访问JSON数组在PHP中,它返回null和警告:提供的foreach无效参数()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!