0

I am trying to send json array to php and insert multiple rows in to table

Problem:

Php:

  1. Not able to access the decode JSON array - array count returns nil
  2. 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 to NSMutableArray and then NSArray. When I parse the NSMutableArray 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;
}

    ?>
3
  • Use var_dump($inputJSON) and make sure there's nothing extra in the input. Also use json_last_error() when json_decode() returns NULL. Commented Apr 7, 2016 at 13:06
  • Thank you. var_dump($inputJSON) gives me this string(0) "" and json_last_error() gives me int(0) Commented Apr 8, 2016 at 4:06
  • If the input JSON is empty, how do you expect to get anything when decoding it? Commented Apr 8, 2016 at 15:48

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Don't see how this can possibly work if $data is null.
var_dump($data) return string(0) "", but when ecode the data and send it to the ios it have the data.It have data ,
There must be something else going on, like you reassigned the variable or you're doing these two steps in different scopes. Also, first you said var_dump($data) is NULL, now you say it's string(0) "". It can't be both. But either way, you can't do $data[0]['location'] with that value of $data.
There's also no location key in the JSON you show in the question.
For this answer to be useful for future readers, you need to explain what was wrong with the original code, and how this fixed it. Otherwise, it's just cargo-cult programming.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.