使用PHP函数用数组覆盖默认的JSON目标



我们构建了一个API,可以使用键直接访问其他社交网络API。

我正在尝试构建一个访问该API的功能。

默认函数已编写并正在工作。

问题

  • 如何指定一个针对JSON数据的新数组?
    • 这将覆盖默认设置。

function SocialAPI($handle, $service, $path="") {
    $handle = strtolower($handle);
    $service = strtolower($service);
    $api = file_get_contents("https://api.service.domain.com/v1/Social?handle=$handle&service=$service");
    if($api !== false) {
        $data = json_decode($api, true);
        if($data !== null) {
            if($service === "twitter") {
                return $data['0']['followers_count'];
            }
            if($service === "instagram") {
                if(!empty($path)) {
                    while($id = array_shift($path)) {
                        echo $data[$id];
                    }
                    return $data;
                } else {
                    return $data['user']['followed_by']['count'];
                }
            }
        } else {
            return false;
        }
    } else {
        return "API call failed.";
    }
}
//Test API Function - ** TO BE DELETED **
echo SocialAPI("JohnDoe", "Instagram", "['user']['full_name']");
exit();
function array_deref($data, $keys) {
    return empty($keys) ? $data
        : array_deref($data[$keys[0]], array_slice($data, 1))
}
function SocialAPI($handle, $service, $path="") {
    $handle = strtolower($handle);
    $service = strtolower($service);
    $api = file_get_contents("https://api.service.domain.com/v1/Social?handle=$handle&service=$service");
    if ($api === false) {
        return "API call failed.";
    }
    $data = json_decode($api, true);
    if($data !== null) {
        return false;
    }
    if ($service === "twitter") {
        if (empty($path)) $path = ['0','followers_count'];
        return array_deref($data, $path);
    } elseif ($service === "instagram") {
        if (empty($path)) $path = ['user','followed_by'];
        return array_deref($data, $path);
    }
}
//Test API Function - ** TO BE DELETED **
echo SocialAPI("JohnDoe", "Instagram", ['user', 'full_name']);
echo SocialAPI("JohnDoe", "Instagram");
exit();

我添加了一个实用程序 array_deref,以递归行走阵列(调用自己处理每个级别)。

最新更新