能不能访问JSON数组在PHP中,它返回null和警告:的foreach提供了无效的参数()(Can

2019-11-04 05:08发布

我试图JSON数组中的表发送到PHP和插入多行

问题:

PHP的:

  1. 不能访问解码JSON阵列 - 阵列计数返回nil
  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;
}

    ?>

Answer 1:

随着神恩典解决我的问题,我原来代码中的错误是,我用于每个所以data.First的访问给我warning.Then从链接http://www.dyn-web.com/tutorials/php- JS / JSON / decode.php ,我得到了这样的访问,那么它的工作。

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

然后我们使用数字和关联数组语法的组合,以访问期望的元件在多维数组。



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