Jump to content
a-ok

PHP Arrays to JSON without []

Recommended Posts

Hi folks,

I want to pass some PHP arrays to JSON. I am managing to do this fine but the issue is that it wraps [] round the array, whereas I need it without [] to use it as geojson within Mapbox (https://www.mapbox.com/mapbox-gl-js/example/popup-on-click/).

<?php
$programme_array = array();
$programmes = $pages->find('parent=programme, sort=sort');
foreach ($programmes as $programme) {
$title = $programme->title;
$url = $programme->url;
$summary = $programme->programme_summary;
$image = $programme->programme_venue_image->url;
$long = $programme->programme_location->lng;
$lat = $programme->programme_location->lat;
$programme_array[] = array(
'type' => 'Feature',
'geometry' => array(
'type' => 'Point',
'coordinates' => [$long,$lat]
),
'properties' => array(
'title' => $title,
'description' => $summary,
'image' => $image,
'url' => $url,
"marker-symbol" => "music"
),
);

}
$programme_json = json_encode($programme_array, true);
?>

[{"type":"Feature","geometry":{"type":"Point","coordinates":["-1.466439","53.376842"]},"properties":{"title":"Site Gallery","description":"Duis arcu tortor, suscipit eget, imperdiet nec, imperdiet iaculis, ipsum. Donec id justo. Aenean tellus metus, bibendum sed, posuere ac, mattis non, nunc. Suspendisse feugiat. Etiam rhoncus.","image":"\/Freelance\/art-sheffield-2016\/site\/assets\/files\/1032\/site_gallery.jpg","url":"\/Freelance\/art-sheffield-2016\/programme\/site-gallery\/","marker-symbol":"music"}},{"type":"Feature","geometry":{"type":"Point","coordinates":["-1.477881","53.374798"]},"properties":{"title":"Moore Street Substation","description":"","image":null,"url":"\/Freelance\/art-sheffield-2016\/programme\/moore-street-substation\/","marker-symbol":"music"}},{"type":"Feature","geometry":{"type":"Point","coordinates":["-1.459620","53.380562"]},"properties":{"title":"S1 Artspace","description":"","image":null,"url":"\/Freelance\/art-sheffield-2016\/programme\/s1-artspace\/","marker-symbol":"music"}}]

Any thoughts? I know this is perhaps more PHP/JSON related question than a PW question but I just wanted to make sure I had this set up correctly.

 

Share this post


Link to post
Share on other sites

Here is some info to help explain what is going on and how to fix it:

http://stackoverflow.com/questions/15559735/no-square-bracket-json-array

http://stackoverflow.com/questions/7109424/remove-the-brackets-in-json

Also, I am curious about the "true" option you are passing - I don't think that is valid, although it may not do any harm either.

Share this post


Link to post
Share on other sites

Thanks for the replies.

From the docs it looks like JSON_FORCE_OBJECT might solve that.

Unfortunately I tried this and it outputs the following (no need for ... "0" or "1" etc)

{"0":{"type":"Feature","geometry":{"type":"Point","coordinates":{"0":"-1.466439","1":"53.376842"}},"properties":{"title":"Site Gallery","description":"Duis arcu tortor, suscipit eget, imperdiet nec, imperdiet iaculis, ipsum. Donec id justo. Aenean tellus metus, bibendum sed, posuere ac, mattis non, nunc. Suspendisse feugiat. Etiam rhoncus.","image":"\/Freelance\/art-sheffield-2016\/site\/assets\/files\/1032\/site_gallery.jpg","url":"\/Freelance\/art-sheffield-2016\/programme\/site-gallery\/","marker-symbol":"music"}},"1":{"type":"Feature","geometry":{"type":"Point","coordinates":{"0":"-1.477881","1":"53.374798"}},"properties":{"title":"Moore Street Substation","description":"","image":null,"url":"\/Freelance\/art-sheffield-2016\/programme\/moore-street-substation\/","marker-symbol":"music"}},"2":{"type":"Feature","geometry":{"type":"Point","coordinates":{"0":"-1.459620","1":"53.380562"}},"properties":{"title":"S1 Artspace","description":"","image":null,"url":"\/Freelance\/art-sheffield-2016\/programme\/s1-artspace\/","marker-symbol":"music"}}}

Share this post


Link to post
Share on other sites

I have come up with the following, which works in terms of formatting BUT it's only returning one item and not three (three children pages to the parent 'programme')?

$geojson = array( 'type' => 'FeatureCollection', 'features' => array());

$programmes = $pages->find('parent=programme, sort=sort');
foreach ($programmes as $programme) {

  $marker = array(
    'type' => 'Feature',
    'properties' => array(
      'title' => $programme->title,
      "marker-symbol" => "music"
    ),
    'geometry' => array(
      'type' => 'Point',
      'coordinates' => array( 
        $programme->programme_location->lng,
        $programme->programme_location->lat
      )
    )
  );
  array_push($geojson['features'], $marker);
}
$programme_json = json_encode($marker, JSON_PRETTY_PRINT);

Any thoughts? If I unpublish the last child, it returns the new 'last child' in programme. Weird?

Share this post


Link to post
Share on other sites

What's even weirder is that if I add the square brackets [ ] to $marker = array( effectively making it $marker[] = array( then it returns all the items BUT it has the square brackets on it.

I'm so deep down the rabbit hole...

Share this post


Link to post
Share on other sites

I know I must be missing something obvious, but wasn't your first post getting you all items? If so, then why not just strip the beginning [ and ending ] and be done with it?

Share this post


Link to post
Share on other sites

I know I must be missing something obvious, but wasn't your first post getting you all items? If so, then why not just strip the beginning [ and ending ] and be done with it?

Yeah I tried that too, but it threw back a JS error saying unexpected token }

$programme_json = substr($programme_json, 1, -1);

Share this post


Link to post
Share on other sites

I'm not sure if that's helpful, but json does only allow for either square-bracketed arrays or keyed objects (therefore the "0": {}). Also the api you linked does use [] brackets for features.

Share this post


Link to post
Share on other sites

This is what I came up with... after much trial and error:

<?php

$geojson = array(
'type' => 'FeatureCollection', 
'features' => array()
);

$programmes = $pages->find('parent=programme, sort=sort');

foreach ($programmes as $programme) {

    $marker = array(
        'type' => 'Feature',
        'properties' => array(
            'title' => $programme->title,
            'url' => $programme->url,
            'summary' => $programme->programme_summary,
            'image' => $programme->programme_venue_image->url
        ),
        'geometry' => array(
            'type' => 'Point',
            'coordinates' => array(
                $programme->programme_location->lng,
                $programme->programme_location->lat
            )
        )
    );
    array_push($geojson['features'], $marker);

}

$programme_json = json_encode($geojson);

?>
Edited by LostKobrakai
Fixed some indentations

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By louisstephens
      So I reread my first draft, and it made absolutely no sense (I deleted it to hopefully better explain myself).  I am trying to make a system (that to me is a bit complicated) utilizing jquery and processwire together. My whole goal is to put a url like https://domain.com/launch?first_name=jim&occupation=builder in a script tag on another site(just a localhost .php page) to then pull out the data for that person and append to divs etc. Basically, the initial script tag would point to "launch" which has a content-type of "application/javascript". Using jquery, I would pull out the persons name and occupation and then make a specific ajax get request to "domain.com/api" (in json format) for a look up of the person. Essentially then I could pull that particular person's information from the json data, and do with it how I please in the "launch" page.  In processwire, I have a page structure like:
      People -Jim Bob (template: person ) --Occupations (template: basic-page) ---Builder (template: occupation) ---Greeter (template: occupation) It is really just a bunch of people with their occupations and a few fields to the occupation template. With the "api" (template: api) url, I was hoping to return all the data (of people) in json format like:
      Example Format:
      { "id": 1, "title": "Jim Bob", "occupations": { "builder": { "id": 44, "title": "Builder", "years_worked": 1, "etc": "ect", }, "Greeter": { "id": 44, "title": "Greeter", "years_worked": 1, "etc": "ect", }, } } Where I get lost is really outputting the page names and nesting in the occupations into json. I have used Pages2JSON before, but I was a bit lost on how to implement what i was thinking.
       
      I have access to all the local host files, but I was hoping to kind of build out a "system" where I could place the script tag/parameters in any project, and be able to interact with the data without doing an ajax call on the actual site. In a way, this would keep processwire handling all the data and requests, and my other "projects" just with a simple script tag. This might all be way too much/over complicated, but I couldn't quite wrap my head around how to achieve it. 
    • By anderson
      Hi,
      For the purpose of learning, as shown in this photo, I created a repeater field "we", then a template, then a page.
      But in /templates/testrepeater.php, I has some problem, the "foreach" part does not work as expected.
      <html> <body> <?php echo "<h1>$page->title</h1><br>"; ?> <? foreach($page->we as $member); ?> <img src="<?php echo $member->images->url; ?>" alt=""> <?php echo $member->wemember; ?><br> <? endforeach;?> </body> </html> Could anybody please help point out my error?
      Thanks in advance.

    • By Arunesh Dutta
      Hello all
      I am newbie.Wanted to know does processwire will allow to display external website content and other sources to my website using API powered by processwire
    • By gregory
      Hi guys, I need help.
      how do I translate Next Page?
      <?php if($page->next->id) {echo "<div class='float-right'><a class='button' href='{$page->next->url}'> Next Page </a></div>";} ?> I usually use this:
      <?php $lang = $user->language->name; if($lang == 'default') {echo "Next Page";} else {echo "Pagina successiva";} ?> or
      <?php echo __("Next Page"); ?> Thanks
    • By nuel
      Hi there
      Basically I want to call code within a ProcessWire page that isn't used as a template. Example: www.mypwpage.com/myphpfile.php
      I have a working PW Website with a couple of pages like /artists, /releases, /videos etc. Now I need a page /download without any editable fields in the backend, just calling some PHP code (that was coded by another guy) containing a form that checks unique download-codes in a second database and starts the download of the desired file. The script is working fine right now as part of a static website, but since I built PW behind the site, this independent «Download Section» of the page doesn't work anymore.
      Right now I have the main file download.php as a page template on a newly created empty page called /download, so until now the form is working (wow). After sending the form containing the download-code, the file check_code.php in a subfolder /site/templates/download is called and that's where I get an error.
      Any help?
×
×
  • Create New...