Richard Downs Richard Downs - 1 month ago 8
iOS Question

needing 2 json_encode lines (outputting to Swift)

I have a problem where my userLogin.php script contains 2x JSON_encode lines.

echo json_encode($userDetails);

echo json_encode($communities);


This is the full userLogin.php script below:

<?php

require ("Conn.php");
require ("MySQLDao.php");

$email = htmlentities($_POST["email"]);
$password = htmlentities($_POST["password"]);

$returnValue = array();


if(empty($email) || empty($password))
{
$returnValue["status"] = "error";
$returnValue["message"] = "Missing required field";
echo json_encode($returnValue);
return;
}

$secure_password = md5($password);

$dao = new MySQLDao();
$dao->openConnection();
$userDetails = $dao->getUserDetailsWithPassword($email,$secure_password);

if(!empty($userDetails))
{
$returnValue["status"] = "Success";
$returnValue["message"] = "User is registered";
echo json_encode($userDetails);
}else{

$returnValue["status"] = "error";
$returnValue["message"] = "User is not found";
echo json_encode($returnValue);
}

//once logged in run function to get list of communities

$communities = array();
$communities = $dao->getCommunities($email);
echo json_encode($communities);

$dao -> closeConnection();

?>


$userDetails
stores the details of the person who has just logged in, such as id, name, email address.

$communities
is an array that stores the names of the different communities a person is a member of. Each member may be part of a different number of communities.

I require both of these arrays as soon as a user logs in, hence having them both in my userLogin.php script. These are returned to Swift and in the case of
$communities
, I will display the contents in a UITableView.

However, I have since learnt that you cannot output multiple JSON blocks as this is a syntax error. (which has reported an error in my Xcode)

How do I overcome this problem?

Answer

Put them in an array:

echo json_encode(array($userDetails, $communities));

Or with some meaningful keys:

echo json_encode(array('userDetails' => $userDetails,
                       'communities' => $communities));