buildnpray
buildnpray

Reputation: 3

How to POST multi-dimensional array to PHP

I have an array of arrays of dictionaries. Example MainArray SubArray1 Dict 1 Dict 2 SubArray2 Dict 1 Dict 2

Here is the code before I send an NSMutableUrlRequest using the string output.

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:itemListArray
                                                   options:kNilOptions error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

Which then goes to

NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];

An NSUrlConnection follows.

The jsonstring output is [[{"Description":"Item1"},{"Description":"Item2"}],[{"Description":"SItem1"},{"Description":"SItem2"}]]

My PHP code is pretty simple and returns the jsonstring as above.

$data1 = $_POST["jsonstring"];
var_dump($data1);

My issue now is I don't know how to separate the arrays. Do I have to set up some string formatting to separate the data? For example, pull all data between each set of brackets []. Then further separate data between all ""?

Is there an easier way to post a multi-dimensional array of dictionaries?

Upvotes: 0

Views: 49

Answers (1)

Juan Bonnett
Juan Bonnett

Reputation: 1853

$data1 = '[[{"Description":"Item1"},{"Description":"Item2"}],[{"Description":"SItem1"},{"Description":"SItem2"}]]';

var_dump(json_decode($data1, true));

or without the true as second parameter to allow objects instead of converting them to arrays

var_dump(json_decode($data1));

OUTPUT:

array(2) {
  [0]=>
  array(2) {
    [0]=>
    array(1) {
      ["Description"]=>
      string(5) "Item1"
    }
    [1]=>
    array(1) {
      ["Description"]=>
      string(5) "Item2"
    }
  }
  [1]=>
  array(2) {
    [0]=>
    array(1) {
      ["Description"]=>
      string(6) "SItem1"
    }
    [1]=>
    array(1) {
      ["Description"]=>
      string(6) "SItem2"
    }
  }
}

Upvotes: 1

Related Questions