$page->id() returns 'field object' instead of string on associative array?

I am trying to json_encode some associative arrays, and am getting unexpected results depending on how the associative array is created.

The following code:

$taxes = ['eu' => 21, 'world' => 0];

… when dumped return:s

Array
(
    [eu] => 21
    [world] => 0
)

… and json_encode returns:

{"eu":21,"world":0}

…as expected !

BUT the following code, which is still supposed to create an associative array:

$options = [];

foreach ($page->children() as $p) {
	$options[$p->id()] = $p->price();
};

…when dumped, returns:

Array
    (
        [shipping-eu] => Kirby\Cms\Field Object
            (
                [price] => 7
            )

        [shipping-eu-framed] => Kirby\Cms\Field Object
            (
                [price] => 13
            )
    )

…and json_encode() returns:

{"shipping-eu":{"value":"7"},"shipping-eu-framed":{"value":"13"},"shipping-spain":{"value":"6"},"shipping-spain-framed":{"value":"10"},"shipping-world":{"value":"9"},"shipping-world-framed":{"value":"15"}}

Why the difference?

Why does $page->id() seems to return here a Field Object instead of a String ?

Thank you

It’s not $p->id() that returns an object, but $p->price() (price() is a field and as such, returns a field object). Change to


foreach ($page->children() as $p) {
	$options[$p->id()] = $p->price()->value();
};

Ah but of course, that makes sense.

Danke!