0

I have the following code for exporting all the items in one of my pods to json. The thing is I don't need all the 130 columns in the json file, but only about 20. Since this will be done for about 150 items I thought I could save some loading time by not printing out all the fields, but I do not know how to do this. For example I only want to print the column value named 'title' for all items in the pod. My code is attached bellow.

<?php
$pods = pods('name', array('orderby' => 'name asc', 'limit' => -1));
$all_companies = $pods->export_data();
if ( !empty( $all_companies ) ) {
    die(json_encode($all_companies);
}else{
    die(json_encode(array('error' => 'No cars found.')));
} 
?>

I thought about doing something like this:

if ( 0 < $all_companies->total() ) {
    while ($all_companies->fetch()) {
        $json .= $all_companies->field('title');
    }
    $json = rtrim($json, ",");
    $json .= '}}';
}
echo $json;

But it doesn't work and also the code becomes very long.

1 Answers1

0

I'd make an array of the names of the twenty fields you want then build an array of those fields for each item, by doing a foreach of those field names passed to Pods::field() inside the while loop. Like this:

    $pods = pods('name', array('orderby' => 'name asc', 'limit' => -1));
    $fields = array( 'field_1', 'field_2' );
    if ( $pods->total() > 0 ) {
        while ( $pods->fetch() ) {
            foreach ( $fields as $field ) {
                $json[ $pods->id() ] = $pods->field( $field );
            }

        }

        $json = json_encode( $json );

    }

Alternatively, you could hack the /pods/<pod> endpoint of our JSON API to accept a list of fields to return as the body of the request. Wouldn't be hard to do, make sure to submit a pull request if you make it work.

JPollock
  • 3,218
  • 4
  • 26
  • 36
  • This worked when I changed $pods->id() to just @field! But the while $pods->fetch() does not seem to work. When I echo the $pods->total() I get 2, which is the number of items I write out, but when I just eco $json only 1 item is printed:S –  Sep 23 '14 at 07:42
  • Nevermind, I was printing it inside the while loop! Thank you for the help :) –  Sep 23 '14 at 09:16