I want to iterate over the objects in a bucket. I REALLY need to paginate this - we have 100's of thousands of objects in the bucket. Our bucket looks like:
bucket/MLS ID/file 1
bucket/MLS ID/file 2
bucket/MLS ID/file 3
... etc
Simplest version of my code follows. I know the value I'm setting into $params['nextToken'] is wrong, I can't figure out how or where to get the right one. $file_objects is a 'Google\Cloud\Storage\ObjectIterator', right?
// temp: pages of 10, out of a total of 100. I really want pages of 100
// out of all (in my test bucket, I have about 700 objects)
$params = [
'prefix' => $mls_id,
'maxResults' => 10,
'resultLimit' => 100,
'fields' => 'items/id,items/name,items/updated,nextPageToken',
'pageToken' => NULL
];
while ( $file_objects = $bucket->objects($params) )
{
foreach ( $file_objects as $object )
{
print "NAME: {$object->name()}\n";
}
// I think that this might need to be encoded somehow?
// or how do I get the requested nextPageToken???
$params['pageToken'] = $file_objects->nextResultToken();
}
So - I don't understand maxResults vs resultLimit. It would seem that resultLimit would be the total that I want to see from my bucket, and maxResults the size of my page. But maxResults doesn't seem to affect anything, while resultLimit does.
maxResults = 100
resultLimit = 10
produces 10 objects.
maxResults = 10
resultLimit = 100
spits out 100 objects.
maxResults = 10
resultLimit = 0
dumps out all 702 in the bucket, with maxResults having no effect at all. And at no point does "$file_objects->nextResultToken();" give me anything.
What am I missing?
The objects method automatically handles pagination for you. It returns an ObjectIterator object.
The resultLimit parameter limits the total number of objects to return across all pages. The maxResults parameter sets the maximum number to return per page.
If you use a foreach over the ObjectIterator object, it'll iterate through all objects, but note that there are also other methods in ObjectIterator, like iterateByPage.
Ok, I think I got it. I found the documentation far too sparse and misleading. The code I came up with:
$params = [
'prefix' => <my prefix here>,
'maxResults' => 100,
//'resultLimit' => 0,
'fields' => 'items/id,items/name,items/updated,nextPageToken',
'pageToken' => NULL
];
// Note: setting 'resultLimit' to 0 does not work, I found the
// docs misleading. If you want all results, don't set it at all
// Get the first set of objects per those parameters
$object_iterator = $bucket->objects($params);
// in order to get the next_result_token, I had to get the current
// object first. If you don't, nextResultToken() always returns
// NULL
$current = $object_iterator->current();
$next_result_token = $object_iterator->nextResultToken();
while ($next_result_token)
{
$object_page_iterator = $object_iterator->iterateByPage();
foreach ($object_page_iterator->current() as $file_object )
{
print " -- {$file_object->name()}\n";
}
// here is where you use the page token retrieved earlier - get
// a new set of objects
$params['pageToken'] = $next_result_token;
$object_iterator = $bucket->objects($params);
// Once again, get the current object before trying to get the
// next result token
$current = $object_iterator->current();
$next_result_token = $object_iterator->nextResultToken();
print "NEXT RESULT TOKEN: {$next_result_token}\n";
}
This seems to work for me, so now I can get to the actual problem. Hope this helps someone.
Related
I'm not sure what is going on here, but I'm trying to retrieve some budgets from a modx/xpdo object and getting unexpected results. From the code below, both foreach loops return the same results [that of the first getMany call. 2 items] if I switch the order of the getmany calls I get only one result for both foreach loops.
$tipa = $this->modx->getObject('Tipa', array('id' => $id, 'token' => $token));
// should retrieve two objects
$tipa_sub_budgets = $tipa->getMany('TipaBudget', array('budget_type_id:!=' => '999'));
foreach($tipa_sub_budgets as $sb){
echo $sb->get('id');
}
// should retrieve one object
$tipa_primary_budgets = $tipa->getMany('TipaBudget', array('budget_type_id' => '999'));
foreach($tipa_primary_budgets as $tb){
echo $tb->get('id');
}
I'm not sure what is happening here. What is the correct way to grab 2 sets of objects from the $tipa object?
I think whereas xPDO::getObject() can be passed the criteria either as an array or an instance of xPDOCriteria, xPDOObject::getMany() expects only an instance of xPDOCriteria meaning the array will not work.
Try passing an instance of xPDOCriteria like so...
$criteria = $this->modx->newQuery("TipdaBudget"); // classname, not the alias
$criteria->where(array("budget_type_id:!=" => 999));
$tipa_sub_budgets = $tipa->getMany("TipaBudget", $criteria);
I'm trying to get products from Magento API with catalogProductList (soap v2) here is my function.
public function get_products() {
$products = array();
$login = $this->login_info();
$proxy = new SoapClient($login['url']);
$sessionId = $proxy->login($login['user'], $login['pass']);
$result = $proxy->catalogProductList($sessionId);
foreach($result as $value) {
$products[] = $proxy->catalogProductInfo($sessionId, $value->product_id);
}
echo "<pre>";
var_dump($products);
echo "</pre>";
}
However because the request it's in a loop it will make for each product a request to Magento API.
I'm wondering if there is a solution to get multiple products info (based on provided product_id) in the same request. Maybe 50 or 100 products info for each request I think will reduce a lot the time of getting all the products.
I have found on http://www.magentocommerce.com/api/soap/introduction.html
$params = array('filter' => array(
array('key' => 'status', 'value' => 'pending'),
array('key' => 'customer_is_guest', 'value' => '1')
));
$result = $client->salesOrderList($sessionId, $params);
but from my understanding it's more about filtering the products so I don't know if it helps too much.
Looks like you're calling the catalogProductList twice, first time outside the loop and the second time inside the loop passing invalid arguments, the doc here is showing that you only need to use the method once passing the session id plus you are able to pass two extra optional arguments (array of filters and the store view id or code) additionally if the returned result catalogProductEntity is not enough you can override that part of the API adding extra product information for example the media images.
I'm able to query my dynamodb tables, but I only want to retrieve the actual value. I don't want the formatting output. This same question has been answered here for Java, but I'm looking for the PHP solution:
Retrieving just the item value from a dynamodb table?
Here is my getitem query:
$response = $dynamodb->getItem(array(
"TableName" => $tableName,
"ConsistentRead" => true,
"Key" => array(
"userguid" => array(Type::STRING => $userguid)
),
"AttributesToGet" => array("token")
));
print_r($response["Item"]["token"]);
Here is the output:
Array
(
[S] => 9d194513
)
All I want to get back is:
9d194513
I assumed the logical answer would be to change the last line to:
print_r($response["Item"]["token"]["S"]);
But then my code doesn't return anything at all. Obviously still learning PHP here, and any help would be appreciated.
Don't use print_r function, just either echo your variables
echo $response["Item"]["token"]["S"];
or store in a variable for later use
$res_token = $response["Item"]["token"]["S"];
You can also use the getPath convenience method built into the Model object that the SDK returns for operations.
echo $response->getPath('Item/token/S');
For more information about working with responses in the SDK, see the Response Models page in the AWS SDK for PHP User Guide.
Though it's an old question but for anyone coming to this page for seeking answer, this is how I have done it.
getItem returns a Resultobject. You can call the get() function of the SDK, which will give you an array containing the exact value.
$params = [
"TableName" => "EpgApiAccessCount",
"Key" => $this->marshalJson('
{
"ApiUserKey": "' . $apiUserkey . '"
}
')
];
$result = $this->client->getitem($params);
if (!$result instanceof ResultInterface) {
return 0;
}
$item = $this->unmarshalItem($result->get("Item"));
return $item["AccessCount"];
Of course your value and table name will be different, and you can print or do anything else with the value.
I am using https://stripe.com/docs/api?lang=php#list_charges to get List all Charges but here they specify
count optional — default is 10 A limit on the number of objects to be
returned. Count can range between 1 and 100 items.
and I have thousands of entries, now how can I get all. Though if I set count to 100 it returns 110 records.
You can use the offset argument.
Once you get the 100 transactions, then make another call by adding offset=100 in URL.
This will bring the next 100 transactions, then make offset=200 and so on.
Update:
offset parameter is partly deprecated: API changelog - 2015-09-23
$charges = \Stripe\Charge::all();
foreach ($charges->autoPagingIterator() as $charge) {
// Do something with $charge
}
Reference.
Yes I got it with offset we can get all records.
Here's a PHP example: \Stripe\Charge::all(array("limit" => 3, "offset" => 10));
A Ruby example:
Stripe::Charge.all(limit: 3, offset:3)
As good as the Stripe API docs are, they could be clearer on how to filter.
source: https://stripe.com/docs/api/php#list_charges, https://stripe.com/docs/api/ruby#list_charges
in case offset is deprecated
$result = [];
$created_at = strtotime($request->end_data);
//created_at should be today's date epoch. search google for epoch
$has_more = false;
$a = 0;
do{
print_r($a);
\Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
$temp = \Stripe\BalanceTransaction::all( array(
'limit' => 100,
'created' => array(
'lte' => $created_at,
)
));
$result = array_merge($temp->data,$result);
$created_at = $temp->data[99]->created_at;
//api returns a parameter has_more(boolean), which means there is more
//data or not so you can also put that in while condition, for ex.
// $has_more = $temp->has_more;
$a++;
}while($a < 5);
dd($result);
this worked for me i was able to get 500 records at once as $a < 5 the api hits 5 times and each time created parameter which is lte (less than equal) changes for each api request and return previous records than current request provide. also i am appending the result of each api call to another result array
Unfortunately you can't.
I can see where such a feature would be nice for accounting purposes or whatever, but it's generally a better user experience to implement some sort of paging when displaying copious amounts of data to the user.
If you need absolute control over how many records to display at a time, I would suggest setting up a webhook on the charge.succeeded event and store your charges locally.
I am trying to come up with a means of working with what could potentially be very large array sets. What I am doing is working with the facebook graph api.
So when a user signs up for a service that I am building, I store their facebook id in a table in my service. The point of this is to allow a user who signs up for my service to find friends of their's who are on facebook and have also signed up through my service to find one another easier.
What I am trying to do currently is take the object that the facebook api returns for the /me/friends data and pass that to a function that I have building a query to my DB for the ID's found in the FB data which works fine. Also while this whole bit is going on I have an array of just facebook id's building up so I can use them in an in_array scenario. As my query only returns facebook id's found matching
While this data is looping through itself to create the query I also update the object to contain one more key/value pair per item on the list which is "are_friends"=> false So far to this point it all works smooth and relatively fast, and I have my query results. Which I am looping over.
So I am at a part where I want to avoid having a loop within a loop. This is where the in_array() bit comes in. Since I created the array of stored fb id's I can now loop over my results to see if there's a match, and in that event I want to take the original object that I appended 'are_friends'=>false to and change the ones in that set that match to "true" instead of false. I just can't think of a good way without looping over the original array inside the loop that is the results array.
So I am hoping someone can help me come up with a solution here without that secondary loop
The array up to this point that starts off as the original looks like
Array(
[data](
[0] => array(
are_fb_friends => false
name => user name
id => 1000
)
[1] => array(
are_fb_friends => false
name => user name
id => 2000
)
[2] => array(
are_fb_friends => false
name => user name
id => 3000
)
)
)
As per request
This is my current code logic, that I am attempting to describe above..
public function fromFB($arr = array())
{
$new_arr = array();
if((is_array($arr))&&(count($arr) > 0))
{
$this->db->select()->from(MEMB_BASIC);
$first_pass = 0;
for($i=0;$i < count($arr);$i++)
{
$arr[$i]['are_fb_friends'] = "false";
$new_arr[] = $arr[$i]['id'];
if($first_pass == 0)
{
$this->db->where('facebookID', $arr[$i]['id']);
}
else
{
$this->db->or_where('facebookID', $arr[$i]['id']);
}
$first_pass++;
}
$this->db->limit(count($arr));
$query = $this->db->get();
if($query->num_rows() > 0)
{
$result = $query->result();
foreach($result as $row)
{
if(in_array($row->facebookID, $new_arr))
{
array_keys($arr, "blue");
}
}
}
}
return $arr;
}
To search a value and get its key in an array, you can use the array_search function which returns the key of the element.
$found_key = array_search($needle, $array);
For multidimensional array search in PHP look at https://stackoverflow.com/a/8102246/648044.
If you're worried about optimization I think you have to try using a query on a database (with proper indexing).
By the way, are you using the Facebook Query Language? If not give it a try, it's useful.