如何将Craft Element API的输出从数组改为哈希结构?
Returning a Hash Structure with Craft Element API
Got it! By default, Craft's Element API spits out an array of your transformed entries, but it's easy to switch that to a hash (associative array) so you can access entries by a unique key like slug or ID. Here's a straightforward solution using a closure endpoint, which gives you full control over the output structure:
<?php namespace Craft; return [ 'endpoints' => [ 'event-name/feed.json' => function() { // Fetch entries matching your section criteria $entries = craft()->elements->getCriteria(ElementType::Entry) ->section('event1') ->find(); // Initialize empty hash to hold our structured data $eventHash = []; foreach ($entries as $entry) { // Transform the speaker list exactly as you were doing before $speakersList = []; foreach ($entry->speakersList as $speaker) { $speakersList[] = [ 'name' => $speaker->name, // Add other speaker fields here (e.g., bio, company) ]; } // Assign the transformed entry to the hash using a unique key // Use $entry->id instead of slug if you prefer numeric keys $eventHash[$entry->slug] = [ 'id' => $entry->id, 'title' => $entry->title, 'speakers' => $speakersList, // Include any other entry fields you need (e.g., event date, description) ]; } // Return the hash—it will automatically serialize to a JSON object return $eventHash; }, ], ];
Key Details:
- We use
craft()->elements->getCriteria()to fetch entries matching your original section filter, just like the default config setup. - For each entry, we keep your existing speaker list transformation logic intact.
- The hash is built using a unique identifier (slug in this example) as the top-level key—this ensures no entries get overwritten, so make sure your chosen key (slug/ID) is unique across all entries in the section.
- Returning the associative array directly from the closure tells the Element API to output a JSON object (hash) instead of a JSON array.
内容的提问来源于stack exchange,提问作者João Marcelo Martins
相关产品推荐
相关产品推荐

