0

I have an object look which contains an object categories from type of array. Currently I have to do the following to display the categories proper in the response.

'endpoints' => [
        'looks.json' => [
            'elementType' => 'Entry',
            'criteria' => ['section' => 'looks'],
            'transformer' => function(EntryModel $entry) {

                // Create an array of all the photo URLs
                $categories = [];
                foreach ($entry->categories as $category) {
                    $object = (object) ['id' => $category->id, 'title' => $category->title];
                    $categories[] = $object;
                }
                return [
                    'title' => $entry->title,
                    'id' => $entry->id,
                    'categories' => $categories
                ];
            },
        ]
    ]

Is there a more elegant way to doing this? Especially because I'll have a lot of more cases where I have to deal with arrays in objects and arrays in objects and so on.

A structure could looks something like this

[
    {
      name: "ads"
      categories: [
         {
            name: "asdasda"
            subCategories: [
                name: "asdasdsa"
           ]
          }
      ]
    }
]
2

Seems a bit unnecessary to cast it to an object. This should work identically:

'transformer' => function(EntryModel $entry) {

    // Create an array of all the photo URLs
    $categories = [];

    foreach ($entry->categories as $category) {
        $categories[] = ['id' => $category->id, 'title' => $category->title];
    }

    return [
        'title' => $entry->title,
        'id' => $entry->id,
        'categories' => $categories
    ];
},

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.