samnabi
February 13, 2017, 4:43pm
1
Say I have a JSON string that looks like this:
[
{
name: "one",
colour: "blue",
size: "small"
},
{
name: "two",
colour: "red",
size: "small"
},
{
name: "three",
colour: "red",
size: "large"
}
]
Do we have a way to treat this like a database with Kirby? I’d really like to be able to use SQL queries on this dataset, like $small_items = $json->where(['size' => 'small']);
There’s lots of information out there on converting databases to JSON in PHP, but not the other way around…
Kirby already ships with what you need to achieve this:
$data = Data::read(__DIR__ . DS . 'data.json'); // converts JSON data to PHP array
$collection = new Collection($data);
$collection->filterBy('size', 'small');
$collection->filterBy('colour', '!=', 'red');
$collection->pluck('size', null, true); // unique sizes
Take a look at the Toolkit collection.php
file to see other available methods. They are almost the same methods as the Pages collection.
2 Likes
samnabi
February 13, 2017, 5:02pm
3
Collections, that’s brilliant. Thank you Pedro.
This is why I love Kirby. It always seems to have just what I need and nothing that I don’t.
1 Like