whats is happening with my code - php

I want to check if notificatins are > 0 then there are notification else then
there are no notifications available, but however if I change status to 1 my rows goes to my second if - else seen, but I want to check how many notifications are seen or unread , but if I change status count like all
public function websocket(){
$data = $this->session->userdata('log');
$user_id = $data['id'];
$timestamp = 1493618633;
// $entryData = array(
// 'category' => $_POST['category'],
// 'title' => $_POST['title'],
// 'article' => $_POST['article'],
// 'when' => time()
// );
$array = $this->notification->getNotifications($timestamp, $user_id);
if ($array > 0) {
if (empty(array_filter(array_column($array, 'status')))) {
echo 'unread';
}else{
echo 'seen';
}
}else{
$this->json(array('msg' => 'there are no notifications available'));
}
$context = new ZMQContext();
$socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'my pusher');
$socket->connect("tcp://localhost:5555");
$socket->send(json_encode('hola'));
}

Based on your code, you're only checking if $array exists (which it does because it's initialized in the line directly above). If using count($array) > 0 or $array.size() > 0 is still returning the undesired result, try throwing a quick and dirty print_r($array) right after the initialization of the variable to check and make sure that your notification system isn't returning an empty or malformed array.

Related

liveBroadcasts->listLiveBroadcasts - even with an ID list - returns no items

I am trying to get attributes of livestreams that are on other channels (not my own) and it seems that everything I try winds up with zero items. This code compiles a list of (up to) 50 active items, and then calls that endpoint with those ids in hand, and the result is returned: 0 items. Not an error, just 0 items.
To clarify: SEARCH returns several items. I collect the VideoID from that collection and request information from list Live Broadcasts. That returns no items.
If I run this code in debug mode, I can see that 50 items are received from search. Checking each of them, I see that they indeed are active livestreams. (OK, I didn't check them all. But I checked many.... https://youtu.be/<VIDEO_ID> revealed active livestreams for each I checked.)
The implication is that only my own livestreams may be retrieved here (youTube documentation doesn't actually say), but that begs the question of the reason for parameters like 'mine' and 'onBehalfOfContentOwner'.
Is there a trick I'm missing here? Or is this endpoint meant to only return my own channel's livestreams? Is there an endpoint that will allow retrieval of random livestreams?
function getRandomLiveStream() {
global $service ;
// We'll search for up to 50 livestreams.. and check each one for a livechat.
// We'll pass the first match as our desired livestream.
$queryParms = [ 'maxResults' => 50
, 'eventType' => 'live'
, 'order' => 'viewCount'
, 'q' => 'DRONE|GAME'
, 'type' => 'video'
] ;
$searchResults = $service->search->listSearch('snippet', $queryParms) ;
if ($searchResults && count($searchResults->items) > 0) {
$ids = [ ] ;
foreach ($searchResults->items as $item) { // Compile the list of up to 50 ids
$ids[] = $item->id->videoId ;
}
$queryParms = [ 'maxResults' => count($ids)
, 'id' => implode(',', $ids)
] ;
$liveBroadcastItems = listLiveBroadcasts($queryParms) ;
if ($liveBroadcastItems) {
foreach ($liveBroadcastItems as $item) {
if (($item->statistics->totalChatCount > 0) // Only if there is an active chat
&& ($item->liveChatId) ) // We need a liveChat ID. If we have that, return this item.
return $item ;
}
}
}
return false ; // Couldn't find a livestream with chat.
}
function listLiveBroadcasts($queryParms) {
global $googleIsHappy ;
global $service ;
global $lov ;
try {
$queryParms['broadcastType'] = 'all' ;
$response = $service->liveBroadcasts->listLiveBroadcasts('snippet,contentDetails,status,statistics', $queryParms);
return $response->items ;
}
catch (Exception $e) {
$googleIsHappy = false ;
$code = $e->getCode() ;
$message = $e->getMessage() ;
$json = $message ;
if ($arr = json_decode($json, true)) {
$message = $arr['error']['message'] ;
}
$string = sprintf("service->%s() failed with code %s, error: %s.\n"
, $serviceName, $code, $message) ;
$lov->writeLogLine($string) ;
return false ;
}
}

Why is there not enough memory in the simplest loop and with an array of 3 elements?

There is a function that displays categories ranging from the very top:
function getFullCategoryName($strCategoryId, $arrCategories)
{
$strCategoryIdPaent = NULL;
$arrCategoryCurr = isset($arrCategories[$strCategoryId]) ? $arrCategories[$strCategoryId] : NULL;
$arrCategoriesNames = [];
while (is_array($arrCategoryCurr)) {
$arrCategoriesNames[] = $arrCategoryCurr['title'];
if ($arrCategoryCurr['parentId'] && isset($arrCategories[$arrCategoryCurr['parentId']])) {
$arrCategoryCurr = $arrCategories[$arrCategoryCurr['parentId']];
} else {
$arrCategoryCurr = NULL;
}
}
krsort($arrCategoriesNames);
return implode(' > ', $arrCategoriesNames);
}
With just 3 array elements, I get an error:
"Allowed memory size of 134217728 bytes exhausted"
I understand that I am using something wrong. Please, help me understand what exactly.
This is my input array:
$arrCategories = array (
193450 =>
array (
'id' => '193450',
'parentId' => '193450',
'title' => 'Blood glucose meter',
),
193451 =>
array (
'id' => '193451',
'parentId' => '193450',
'title' => 'Sugar test strips',
),
193452 =>
array (
'id' => '193452',
'parentId' => '193452',
'title' => 'Blood glucose meter',
),
);
This is the call to the function:
$strCategoryId = 193450;
getFullCategoryName($strCategoryId, $arrCategories);
The while (is_array($arrCategoryCurr)) loop never ends as the else block of $arrCategoryCurr = NULL; is never called.
This happens because you have a loop where a node id is the same as his parent id. Look at your array:
....
'id' => '193450',
'parentId' => '193450',
...
To fix it modify the if statement to:
if ($arrCategoryCurr['parentId'] && $arrCategoryCurr['parentId'] != $arrCategoryCurr['id'] && isset($arrCategories[$arrCategoryCurr['parentId']])) {
Your (sample) data has an issue based on my reading of your function.
The parentId and index are the same in some items. This would create an infinite loop based on what I can work out from the question.
A better structure would be something like the following, with some error checking in the loop:
function getFullCategoryName($strCategoryId, $arrCategories) {
// set a base / default value
$arrCategoriesNames = [];
// do we even have anything to work with?
if (isset($arrCategories[$strCategoryId])) {
// at least one entry
do {
// get the title
$arrCategoriesNames[] = $arrCategories[$strCategoryId]['title'];
// get the next id and error check the data
if ((isset($arrCategories[$strCategoryId]['parentId'])) &&
($strCategoryId != $arrCategories[$strCategoryId]['parentId'])) {
// next index found and not the same
$strCategoryId = $arrCategories[$strCategoryId]['parentId'];
} else {
// either no parentId or a parentId that matches the current
// index. If that is the case, go no further.
$strCategoryId = false;
}
// you could add another error check if you like.
// if (count($arrCategoriesNames) == count($arrCategories)) {
// // go no further as data has a loop
// $strCategoryId = false;
// }
} while($strCategoryId);
// sort the data? why?
krsort($arrCategoriesNames);
}
// return a string
return implode(' > ', $arrCategoriesNames);
}
And testing you sample array;
$result = getFullCategoryName(193450,$arrCategories);
var_dump($result);
Returns the following:
string(19) "Blood glucose meter"

Issues with paging through failure and rejection events returned by mailgun's api

So, I've developed the following code:
const MAILGUN_API_MAX_LIMIT = 300; //max in documentation
$mgClient = new Mailgun\Mailgun("<mailgun_key>");
$domain = "<my_domain>";
$resultItems = array();
try {
$result = null;
$endTime_Epoch = time();
$startTime_Epoch = $endTime_Epoch - 1440000; //400 hours
$queryParams = array(
'begin' => $endTime_Epoch,
'end' => $startTime_Epoch,
'limit' => MAILGUN_API_MAX_LIMIT,
'ascending' => 'no',
'event' => 'rejected OR failed',
);
$request_url = "$domain/events";
do {
$result = $mgClient->get($request_url, $queryParams);
if(!$result->http_response_body) {
/*...*/
} else if($result->http_response_code != 200) {
/*...*/
} else {
$resultItems[] = $result->http_response_body->items;
if(count($result->http_response_body->items) == MAILGUN_API_MAX_LIMIT) {
$request_url = $result->http_repsonse_body->paging->next;
}
}
} while($result && $result->http_response_body && count($result->http_response_body->items) == MAILGUN_API_MAX_LIMIT);
} catch (Exception $e) {
echo $e->getMessage()
}
But I'm having trouble getting it to page through the next set of requests if the limit ever gets hit (it probably won't, but it'd be bad in the event that something happened that made it happen).
I've tried reading mailgun's api doc, but i cannot, for the life of me, figure out what it is talking about with this:
require 'vendor/autoload.php';
use Mailgun\Mailgun;
# Instantiate the client.
$mgClient = new Mailgun('YOUR_API_KEY');
$domain = 'YOUR_DOMAIN_NAME';
$nextPage = 'W3siYSI6IGZhbHNlLC';
# Make the call to the client.
$result = $mgClient->get("$domain/events/$nextPage");
But i can't figure out what that $nextPage is supposed to be. I've tried peeling off the start of the paging->next so it just ends up being $domain/events/, but that doesn't seem to be paging though it. I'm not really sure what to do here, or even what I'm supposed to do.
I know this is a bit later than you would've hoped, but I've also been doing some stuff with the Mailgun and PHP lately.
So $nextPage is a value provided after your first API requests, so you don't need it at the start. Simply make your normal request like so
$result = $mailgun->get("$domain/events", $queryString);
// then we can get our 'Next Page' uri provided by the request
$nextURI = $result->http_response_body->paging->next;
// now we can use this to grab our next page of results
$secondPageResults = $mailgun->get($nextURI, $queryString);
Once thing worth noting though, is that Mailgun seems to always provide a 'next' link even when you've got all the results you want.
In my project I collected all results using a while loop after getting my initial records:
$hasNext = count($items) >= $queryLimit;
while($hasNext) {
$nextResult = $mailgun->get($lastResult->http_response_body->paging->next, $queryString);
$nextItems = $nextResult->http_response_body->items;
$items = array_merge($items, $nextItems);
$hasNext = count($nextItems) >= $queryLimit;
$lastResult = $nextResult;
}
Hope this helps!

How do I implement search filter query using mongodb?

i have few search filter user like the following image. User can select any one two or both
these are my filters language,format and status I have written a query but its not working
$lang_id =2;
$format = ''; //user not selected
$status = ''; //user not selected
$request = $collection->find(array
( '$and' => array(
array(
'language' => $lang_id ,
),
array(
'format' => $format,
),
array(
'status' => $status,
)
)
));
I have check with or also then also its not working
if filters are empty no need to find the empty field but if it is not empty need to find the field .
Please give me a solution I am new in mongodb
Thank you
As a solution to above mentioned issue please try executing following code snippet
$lang_id = 2;
$format = ''; //user not selected
$status = ''; //user not selected
$filter=array();
if(!empty($lang_id))
{
$filter['language']=$lang_id;
}
if(!empty($format))
{
$filter['format']=$format;
}
if(!empty($status))
{
$filter['status']=$status;
}
$request = $collection->find($filter);

PHP Arrays - How to use Multiple variables in array

I have a product import code for Magento that assigns inventory (qty) to a warehouse location (stock_id). The information is passed in an array however my working knowledge of arrays isn't that flash so I'm sure I'm not doing this correctly.
The import is currently done like this however I'm sure it's not the most efficient as I'm saving the product twice.
This will assign a qty of 100 to location 1 (stock_id 1), save the product, then assign a qty of 200 to location 2 (stock_id 2) and then save the product again.
$stocksData = $product->getStocksData();
if (!$stockData) {
$stockData = array();
}
$stockData['stock_id'] = 1;
$stockData['qty'] = 100;
$stocksData[$stockId] = $stockData;
$product->setStocksData($stocksData);
$product->setCreatedAt(strtotime('now'));
try {
$product->save();
echo "Successful";
}
catch (Exception $ex) {
echo 'There was an error :<br/>' .$ex;
}
$stocksData = $product->getStocksData();
if (!$stockData) {
$stockData = array();
}
$stockData['stock_id'] = 2;
$stockData['qty'] = 200;
$stocksData[$stockId] = $stockData;
$product->setStocksData($stocksData);
$product->setCreatedAt(strtotime('now'));
try {
$product->save();
echo "Successful";
}
catch (Exception $ex) {
echo 'There was an error :<br/>' .$ex;
}
What I'm trying to achieve is to set all of the values in the array and save once as this will take a lot of load off the script.
I've been playing around with stuff like this, however haven't got anywhere and usually end up with errors:
$stocksData = $product->getStocksData();
if (!$stockData) {
$stockData = array();
}
$stockData = array(
[$stockData['stock_id'] = 1] => $stockData['qty'] = 100,
[$stockData['stock_id'] = 2] => $stockData['qty'] = 200
);
$stocksData[$stockId] = $stockData;
$product->setStocksData($stocksData);
I'm assuming it's possible to have all of this information in one array but I'm just not sure how.
There are a lot of ways to initialize an array in php.
$stocksData = array(
'key' => 'value',
'myarr' => array(
'nested' => 'array',
1,
),
'id_copy' => $stocksData['id'],
'qty' => $stocksData['stock_id'] == 1 ? 100 : 200,
);
For a full explanation of array syntax, check out php's Array documentation. Also note my usage of the ternary operator. You can get around using this syntax by saying something like:
if ($stocksData['id'] == 1) {
$stocksData['qty'] = 100;
}
else {
$stocksData['qty'] = 200;
}
Edit:
For your specific use case of combining the requests, take a look below:
$stocksData = $product->getStocksData();
$stocksData[1] = array(
'stock_id' => 1,
'qty' => 100,
);
$stocksData[2] = array(
'stock_id' => 2,
'qty' => 200,
);
$product->setStocksData($stocksData);

Categories