Link to home
Start Free TrialLog in
Avatar of CalmSoul
CalmSoulFlag for United States of America

asked on

keep filling the array with URL until false

I have the following code - I would like to keep filling the array with URL https://api.dailymotion.com/user/cricshare/videos?page=1&limit=100 until JSON response"has_more":false

For example:
First URL:
https://api.dailymotion.com/user/cricshare/videos?page=1&limit=100 => "has_more":true
put URL in array and get next URL
Second URL:
https://api.dailymotion.com/user/cricshare/videos?page=2&limit=100 => "has_more":true
put URL in array and get next URL
Third URL:
https://api.dailymotion.com/user/cricshare/videos?page=2&limit=100 => "has_more":false
don't get any URL finish the array as "has_more":false

<?php


error_reporting(E_ALL);

$urls = array(
    'https://api.dailymotion.com/user/cricshare/videos?page=1&limit=100',
    'https://api.dailymotion.com/user/cricshare/videos?page=2&limit=100',
    'https://api.dailymotion.com/user/cricshare/videos?page=3&limit=100'
);

$sets = array();
foreach ($urls as $url) {
    $json   = file_get_contents($url);
    $data   = json_decode($json);
    $sets[] = $data;
}

$new = json_encode($sets, JSON_PRETTY_PRINT);
echo '<pre>';
echo $new;

?>

Open in new window

SOLUTION
Avatar of Phil Phillips
Phil Phillips
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Variation on Phil_Phillips solution (which works very well)...

This returns only the "lists" from each of the URLs.  The return value is one long array that merges the lists.

<?php // demo/temp_phil.php

/**
 * See http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28635433.html
 */
error_reporting(E_ALL);

$sets = array();
$page = 1;
do
{
    $url = sprintf("https://api.dailymotion.com/user/cricshare/videos?page=%d&limit=100", $page);
    $data = json_decode(file_get_contents($url));
    $hasMore = $data->has_more;
    $sets = array_merge($sets, $data->list);
    $page++;
} while ($hasMore);

$new = json_encode($sets, JSON_PRETTY_PRINT);
echo '<pre>';
echo $new;

Open in new window

Avatar of CalmSoul

ASKER

Thanks Phil and Ray!!

How about if I need to do this ? Getting for multi accounts

$useraccounts = array("cricshare", "cricshare1", "cricshare2");


$url = sprintf("https://api.dailymotion.com/user/$useraccounts/videos?page=%d&limit=100", $page);

Open in new window

ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial