简体   繁体   English

用PHP和JSON创建第三方API

[英]creating 3rd party API with PHP and JSON

I have an API for my website, I want to use it for mobile applications. 我的网站有一个API,我想将其用于移动应用程序。 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. 但是问题是这些API提供了很多不需要的数据,因此我想制作一个第三方API,以过滤从第一个API获得的数据。

as an example, I want to filter article list data obtained from the first API, I've done is the following: 例如,我要过滤从第一个API获得的文章列表数据,我做了以下工作:

<?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. 所以我的问题是,我制作的API并未首先显示从API获得的所有文章列表。

i use $_GET['kat']; 我用$_GET['kat']; to filter articles categories 筛选文章类别

what should I edit in my script? 我应该在脚本中编辑什么?

You are loading $list in a loop so 您正在循环加载$list ,因此

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

is over writing $list each time round the loop! 每次循环都写$list了!

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. 现在,您将创建一个数组数组,其中包含循环数据的所有结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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