duangongqiong6958 2018-08-07 15:35
浏览 33

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

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?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 mmocr的训练错误,结果全为0
    • ¥15 python的qt5界面
    • ¥15 无线电能传输系统MATLAB仿真问题
    • ¥50 如何用脚本实现输入法的热键设置
    • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
    • ¥30 深度学习,前后端连接
    • ¥15 孟德尔随机化结果不一致
    • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
    • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
    • ¥15 谁有desed数据集呀