无法访问php中的json数组,它返回null和警告:为foreach()提供的参数无效


Cannot able to access json array in php , it returns null and Warning: Invalid argument supplied for foreach()

我正在尝试将json数组发送到php,并在表中插入多行

问题:

Php:

  1. 无法访问解码JSON数组-数组计数返回零
  2. 警告:为foreach()提供的参数无效

当我打印JSON字符串时,它会给我以下数据

[
    {
        "email" : "",
        "Name" : "Ddd",
        "contact2" : "",
        "ontact1" : ""
    },
    {
        "email" : "",
        "Name" : "Ddd",
        "contact2" : "",
        "contact1" : ""
    },
    {
        "email" : "",
        "Name" : "Dddddr",
        "contact2" : "",
        "contact1" : ""
    }
]

但当我试图使用php访问它时,它显示了一个错误

PHP代码:

<?php
    $inputJSON = file_get_contents('php://input');
    $array = json_decode($inputJSON, true);
    echo count($array);
    foreach($array as $item) {
        $uses = $item['Name'];
        echo $uses;
    }
?>

错误:

警告:为foreach()提供的参数无效

所以我用在php中测试了这个数组

Isarray() || Isobject funtion but it print null
Count() funcions provide 0 
 var_dump($array); result NULL

但我在iOS中解码数组并检查结果,它会将数组作为响应

echo json_encode($array);

但是在php中,我无法访问数组。

不确定iOS代码中是否有任何错误。在iOS中,我有NSMutableDictionary,它存储到NSMutableArray,然后存储到NSArray。当我解析NSMutableArray时,我会遇到同样的问题。

iOS代码:

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")
}

保存到服务器:

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()
}    

注意:当我签入php时,它就像这样工作。这就是当我直接给Jsonstring或jsonarray时,它就起作用了。

<?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;
}
    ?>

上帝保佑,恩典解决了我的问题我最初代码中的错误是,访问数据。首先我使用了每个,所以它给了我警告。然后从链接http://www.dyn-web.com/tutorials/php-js/json/decode.php,我得到了这样的访问,然后它工作了。

       $location = $data[0]['email'];

然后,我们使用数字和关联数组语法的组合来访问多维数组中所需的元素。