0

I'm trying to build an array of objects in PHP and then echo that for use in Swift. I can get a single object to show up in Swift when I do println on the JSON object, but I need many objects echoed.

class catRow{
    public $id;
    public $person;
    public $item;
    public $descr;
    public $link;
    public $price;
}

$prepare_string = "SELECT * FROM items ORDER BY person LIMIT 5";
$stmt = $dbh->prepare($prepare_string);
$stmt->execute();
while($row = $stmt->fetch()){
    $catRow = new stdClass;
    $catRow-> id = $row['id'];
    $catRow-> person = $row['person'];
    $catRow-> item = $row['item'];
    $catRow-> descr = $row['descr'];
    $catRow-> link = $row['link'];
    $catRow-> price = $row['price'];
    $allRows[] = $catRow;
}

echo json_encode($allRows);

And then on the Swift side I have (summarized):

let catalogueRows: NSDIctionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as NSDictionary

println(catalogueRows)

This works when I echo $catRow but I want to echo each row from that table in my database.

2
  • what println(catalogueRows) prints? Commented Dec 11, 2014 at 5:49
  • The fetch function returns a boolean, so I don't think your while loop is right. I'd call bind_result to bind these results to variables, and then use those when defining catRow. Or alternatively, use get_result (if you're using the MySQL native driver only), and then use fetch_assoc or fetch_array to retrieve data for the $row variable like that. Commented Dec 11, 2014 at 6:27

1 Answer 1

1

The allRows is an array, not a dictionary. So you should cast catalogueRows to a NSArray:

var error: NSError?
if let catalogueRows = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: &error) as? NSArray {
    // successful, do something with `catalogueRows`
    println(catalogueRows)
} else {
    println("parse error: /(error)")
}

Or, perhaps even better, cast it to an array of Swift dictionaries:

var error: NSError?
if let catalogueRows = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: &error) as? [[String: AnyObject]] {
    // successful, do something with `catalogueRows`
    println(catalogueRows)
} else {
    println("parse error: /(error)")
}

Note, in both of these cases, I (a) capture the error object; and (b) use the if let syntax to gracefully handle failures.

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

Comments

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.