1

I'm using json_encode on a two dimensional array in a PHP script like so:

$myjsons[] = json_encode(array($runners));

And also MANY single dimensional arrays later in the script:

$myjsons[] = json_encode(array($mrow));

I then echo after encoding the entire array at the end of the script:

echo json_encode($myjsons);

I'm working on an iOS app that communications with this service. Well, at least it is suppose to. Here is the iOS code minus error checking: (I'm using JSONKit, btw)

NSMutableURLRequest *urlReq = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:kStartRaceURL]];
[urlReq setHTTPMethod:@"GET"];

NSError *requestError;
NSURLResponse *urlResponse = nil;

NSData *response = [NSURLConnection sendSynchronousRequest:urlReq returningResponse:&urlResponse error:&requestError];

NSArray *deserializedData = [response objectFromJSONData];

The deserializedData is an array, but all objects within it are strings. I put arrays in it though, as shown in the PHP, so why are they NSString's? Where is the problem with the implementation? Or should I do something with the NSString's?

1 Answer 1

3

json_encode returns a string, so when you put those in an array, you get an array of strings. When you json_encode that array, you get a (JSON) string array of strings.

To fix this, you should first merge all your arrays into one large array, and then only call json_encode once on that final array. Example:

$myjsons[] = array($runners);
$myjsons[] = array($mrow);

echo json_encode($myjsons); // Correct JSON as you expect it.
Sign up to request clarification or add additional context in comments.

1 Comment

Honestly, I was thinking that was the problem, though PHP is by no means my language of choice. Thank you!

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.