简体   繁体   中英

creating 3rd party API with PHP and JSON

I have an API for my website, I want to use it for mobile applications. but the problem is these APIs provide a lot of data that is not needed, so I wanted to make a third-party API that filter data obtained from the first API.

as an example, I want to filter article list data obtained from the first API, I've done is the following:

<?php
  header('Content-type: application/json');
  if (isset($_GET['kat'])) {
    $url = $_GET['kat'];
  } else {
    $url = null;
  }

  $app_list = file_get_contents('http://localhost/api/articles/lists');
  $app_list = json_decode($app_list, true);
  foreach ($app_list as $app) {
    $id = $app['id'];
    $uid = $app['user_id'];
    $cat = $app['category'];
    $tgl = $app['created_date'];
    $img = $app['image'];
    $posttipe = $app['post_user_type'];
    $komen = $app['count_comment'];
    $likes = $app['count_likes'];
    $c = substr($app['content'], 0, 100);
    $content= $c . "...";
    if ($cat == $url || !$url) {
      $list = array("id" => $id, "user_id" => $uid, "category" => $cat, "image" => $img, "post_user_type" => $posttipe, "count_comment" => $komen, "count_likes" => $likes, "created_date" => $tgl, "content" => $content);
    }
  }
  echo json_encode($list);
?>

that so my problem is, that the API I made do not show all the list of articles obtained from API first.

i use $_GET['kat']; to filter articles categories

what should I edit in my script?

You are loading $list in a loop so

$list = array("id" => $id, .....);

is over writing $list each time round the loop!

Change this line to

    $list[] = array("id" => $id, .....);

And now you will be creating an array of arrays, containing all the results of your looped data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM