如何将集合转换为带有嵌套数组的自定义键/值数组

时间:2018-08-07 15:35:11

标签: php laravel laravel-5

我需要将我的收藏集返回到Chatfuel(特别是Messenger)可以理解的数组中。调用User::get()时,我得到了所有用户的集合,但是我需要将其映射到JSON array that Chatfuel expects

以前(当我使用原始PHP而没有框架时),是这样做的:

<?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);

尽管完成了工作,但它并不是真正可读或干净的

获取现有集合并将其映射到我需要的自定义键/值数组的最佳方法是什么?

0 个答案:

没有答案