I need to return my collection into an array that Chatfuel, and specifically Messenger, understands. When calling User::get()
, I get a collection of all the users, but I need to map it out to the JSON array that Chatfuel expects.
I've previously (when I was using raw PHP and no framework), done it like so:
<?php
$det = array();
while ($row = mysqli_fetch_assoc($results)) {
$row_array['title'] = $row['book-title'] . " | " . $row['edition'] . " Edition";
$row_array['image_url'] = $row['image-url'];
$row_array['subtitle'] = $row['author'];
if (!empty($_SESSION['loggedinuniid'])) {
$urllink = "https://example.com/textbook/?isbn=" . $row['isbn'] . '&uni=' . $_SESSION['loggedinuniid'] . '&submit';
} else {
$urllink = "https://example.com/textbook/?isbn=" . $row['isbn'] . '&submit';
}
$row_array['item_url'] = $urllink;
if ($row['rrs'] == 0) {
$row_array['buttons'] = array(array('type' => 'web_url', 'url' => $urllink, 'title' => 'See Textbook'));
} else {
$row_array['buttons'] = array(array('type' => 'web_url', 'url' => $urllink . '#selling', 'title' => 'Buy Textbook (' . $row['rrs'] . ')'));
}
array_push($det, $row_array);
}
$row_array['title'] = "Find Textbooks on example";
$row_array['subtitle'] = "Search for textbooks sold by your classmates at uni!";
$row_array['image_url'] = "";
$urllink = "https://example.com/";
$row_array['item_url'] = $urllink;
$row_array['buttons'] = array(array('type' => 'web_url', 'url' => $urllink, 'title' => 'See All Textbooks'));
array_push($det, $row_array);
$final = array(
'messages' => array(
array("attachment" => array(
"type" => "template", "payload" => array(
"template_type" => "generic", "elements" => $det,
),
),
),
array("text" => "Hope this helps! You can also always search on example.com!"),
),
);
$post_data = json_encode($final);
exit($post_data);
And, while it got the job done, it isn't really readable or clean.
What's the best way to take an existing collection, and map it out to a custom key/value array I need?