Displaying array data from REST API

Kirby-newbie here, trying to get array data from an API to virtual pages.

I followed the setup here and everything is working fine apart from the info that is in array format.

The source is in JSON and it’s something like this:

[{"lastname":"Doe","firstname":"John","roles":["senior","developer","staff"]}]

I can get the array into a field in the page model, but after that, I’m stumped. I have tried to go through the array data using for and foreach, but I get an error about “Array to string conversion”. Using something like $page->roles()->toString() does the same thing where as $page->roles()->get() doesn’t return anything. Yup, I have been trying a lot of random stuff already :wink:

If I use dump($page->roles()), the contents is there, but how can I get the info out in plain “value1, value2, value3” format?

Hey, and welcome the forum. Must admit that I don’t quite understand. How did you assign the fields from the API to your page model? Could you please post the model?

<?php

class OsaajatPage extends Page
{
    public function children()
    {
        $results = [];
        $pages   = [];
        $request = Remote::get('url-to-source');

        if ($request->code() === 200) {
            $results = $request->json(true);
        }

        foreach ($results as $key => $osaaja) {
            $pages[] = [
                'slug'     => Str::slug($osaaja['lastname'].'-'.$osaaja['firstname']),
                'num'      => $key+1,
                'template' => 'osaaja',
                'model'    => 'osaaja',
                'content'  => [
                    'title'    => $osaaja['lastname'].' '.$osaaja['firstname'],
					'roles'    => $osaaja['roles']
                ]
            ];
        }

        return Pages::factory($pages, $this);
    }
}

Here I can get a single value to a field if I use the key, e.g. ‘roles’ => $osaaja[‘roles’][‘0’]. I can’t use that in the page template, though.

Ok, since that’s an array, and you probably want to store it in a multiselect field as a comma separated list, you have to implode it:

'roles'    => implode(', ', $osaaja['roles']),

That works, yay!

A follow-up to this: there are e.g. address fields that are stored as arrays as well. Street address, post code and city are separate fields, also stored as arrays because one person can have several addresses in the source info.

I was going to make a for/foreach loop to go through the data in the fields, but is there a quicker or a more elegant way to do this?

Need to see the raw data. And you have to store this in a structure field (which needs yaml encoded data)

It’s ok, I got it working using explode and for clauses. Not the prettiest, but works in this case.

Thank you for your help!