_jack
June 21, 2019, 1:23pm
1
Hello, is it possible to simplify JSON data into the same level array like this example:
{
"url": [
"http:\/\/image1.jpg",
"http:\/\/image2.jpg",
"http:\/\/image3.jpg",
"http:\/\/image4.jpg"
]
}
My current .json file looks like this:
<?php
$data = $pages->find('images')->images();
foreach($data as $file) {
$json[] = array(
'url' => $file->url(),
);
}
echo json_encode($json);
which is giving me data like this:
[
{"url":"http:\/\/image1.jpg"},
{"url":"http:\/\/image2.jpg"},
{"url":"http:\/\/image3.jpg"},
{"url":"http:\/\/image4.jpg"}
]
Should be something like this:
<?php
$data = $pages->find('images')->images();
$urls = [];
foreach($data as $file) {
$urls[] = $file->url();
}
$json['url'] = $urls;
echo json_encode($json);
1 Like
_jack
June 22, 2019, 3:39am
4
Hi again
How about with the same thing with children page titles?
<?php
$data = $pages->find('words')->children();
$urls = [];
foreach($data as $file) {
$urls[] = $file->title();
}
$json['title'] = $urls;
echo json_encode($json);
is giving me:
{
"title": [
{
"value": "page title 1"
},
{
"value": "page title 2"
},
{
"value": "page title 3"
},
]
}
but Iād like
{
"title": [
"page title 1",
"page title 2",
"page title 3",
]
}
What is the $urls
? Can that be anything? Thanks very much for your help
_jack
June 22, 2019, 4:11am
5
I got it! Added (string)
before $file->title();
Exactly, you need a string. While $file->url()
returns a string, $file->title()
returns a field object. As @bnomei pointed out above, you can get the string value from a field using the value()
method. It is actually preferable to use this method over a simple casting to string.
1 Like