I am using text area to search the number that user can key in 10 mobile numbers maximum on 1 time. When I try to test with 2 numbers, if I key in 1st number which is have its profile in our db the output is correct. But if I key in 1st value with number that not have its profile in our db the output become incorrect and it does not looping the 2nd value. I got an error illegal offset string. Can anyone help me on this case? Thank you in advance
if (isset($_POST['search']) && $_POST['search'] == 'Search') {
$police = new police();
$user = $_SESSION['username'];
$searchuser = $_POST['searchby'];
$_SESSION['searchby'] = $_POST['searchby'];
$param = explode("\n", trim($_POST['info']));
for ($i = 0; $i < count($param); $i++) {
$param[$i] = str_replace(array("\r", "\n", "\r\n"), "", $param[$i]);
}
try {
if ($_POST['searchby'] == 'select') {
throw new Exception("Please select your identity search");
}
} catch (Exception $ex) {
$errmsg = $ex->getMessage();
$tbs->VarRef['searchFail'] = 'true';
$tbs->VarRef['searchFailMsg'] = $errmsg;
$user = $_SESSION['username'];
}
if (isset($param) && $_POST['searchby'] == 'msisdn') {
$ptrnmsisdn = "/^(\+?6?01)[0|1|2|3|4|6|7|8|9]\-*[0-9]{7,8}$/";
for ($i = 0; $i < count($param); $i++) {
$param[$i] = preg_replace("/^(6)(\d+)/", "$2", $param[$i]);
}
try {
if (empty($param)) {
throw new Exception("Please enter your search");
} else {
foreach ($param as $item) {
if (!preg_match($ptrnmsisdn, $item)) {
throw new Exception("Please enter correct mobile number");
}
}
}
$tbs->LoadTemplate('msisdnprofile1.html');
//$_SESSION["msisdnlist"] = $police->getSubsInfo($param[0],$searchmsisdn);
try {
$searchResult = array();
foreach ($param as $paramValue) {
$search = "NRIC";
$msisdnList = $police->getSubsInfo($paramValue, $search);
$searchResult[$paramValue] = $msisdnList;
}
} catch (Exception $ex) {
$searchResult[$paramValue] = $ex->getMessage();
}
$listMsisdn = "";
$arryTemp = array();
foreach ($searchResult as $searchValue => $subValue) {
array_push($arryTemp, $searchValue);
$listMsisdn .= '<div>
<h3>' . $searchValue . '</h3>
<table>
<thead>
<tr>
<th width="300">Mobile Number</th>
<th width="300">Status</th>
<th width="300">View</th>
</tr>
</thead>
<tbody>
';
$listMsisdn .= '<tr>
' . $subValue['msisdn'] . '
' . $subValue['Reg_Status'] . '
';
$listMsisdn .= ' </tbody>
</table>
';
}
$_SESSION['$searchValue'] = $searchValue;
$_SESSION['$listMsisdn'] = $listMsisdn;
$_SESSION['$listOfSearchValue'] = $arryTemp;
$tbs->Show();
die();
} catch (Exception $ex) {
$user = $_SESSION['username'];
$errmsg = $ex->getMessage();
$tbs->VarRef['searchFail'] = 'true';
$tbs->VarRef['searchFailMsg'] = $errmsg;
}
}
}
You have your try/catch around the whole foreach loop. So if there's an error in any of the parameters, the loop will stop at that point. You need to put it just around the call to getSubsInfo() so you can continue the loop with the rest of the $param array.
$searchResult = array();
$search = "NRIC";
foreach ($param as $paramValue) {
try {
$msisdnList = $police->getSubsInfo($paramValue, $search);
$searchResult[$paramValue] = $msisdnList;
} catch (Exception $ex) {
$searchResult[$paramValue] = $ex->getMessage();
}
}
Related
in view I can fetch all categories:
<?php foreach ($this->parent_categories as $category): ?>
<?php endforeach ?>
Now controller:
$data['parent_categories'] = $this->category_model->get_parent_categories_tree($category);
and finally model category:
//get parent categories tree
public function get_parent_categories_tree($category, $only_visible = true)
{
if (empty($category)) {
return array();
}
//get cached data
$key = "parent_categories_tree_all";
if ($only_visible == true) {
$key = "parent_categories_tree";
}
$key = $key . "_lang_" . $this->selected_lang->id;
$result_cache = get_cached_data($this, $key, "st");
if (!empty($result_cache)) {
if (!empty($result_cache[$category->id])) {
return $result_cache[$category->id];
}
} else {
$result_cache = array();
}
$parent_tree = $category->parent_tree;
$ids = array();
$str_sort = "";
if (!empty($parent_tree)) {
$array = explode(',', $parent_tree);
if (!empty($array)) {
foreach ($array as $item) {
array_push($ids, intval($item));
if ($str_sort == "") {
$str_sort = intval($item);
} else {
$str_sort .= "," . intval($item);
}
}
}
}
if (!in_array($category->id, $ids)) {
array_push($ids, $category->id);
if ($str_sort == "") {
$str_sort = $category->id;
} else {
$str_sort .= "," . $category->id;
}
}
$this->build_query($this->selected_lang->id, true);
$this->db->where_in('categories.id', $ids, FALSE);
if ($only_visible == true) {
$this->db->where('categories.visibility', 1);
}
$this->db->order_by('FIELD(id, ' . $str_sort . ')');
$result = $this->db->get('categories')->result();
$result_cache[$category->id] = $result;
set_cache_data($this, $key, $result_cache, "st");
return $result;
}
but the problem is currently I fetch with this code all categories without limit. How to get first 10 records?
I try:
$result = $this->db->get('categories', 10)->result();
But this not work and still fetch all categories. Can anyone help me resolve this issue? Maybe I do something wrong. Thanks for check.
Introduction
Hi, I hope everyone is doing great. I am a little advance to beginner level in Laravel and developing a system where I have to use Instagram API to get all the data against different hashtags.
These hashtags could be 1, or 2, or even more. Here is the code that I am sharing, this code is taking too much time to run because of the nested loops in it. Can anyone who is expert share his/her knowledge and give me suggestions on how to improve this piece of code?
The code
public function getHastagMediaByID($token)
{
$client = new \GuzzleHttp\Client();
$event_hashtag = $this->event->hashtag;
$hashtagArray = explode(',', $event_hashtag);
$hashtagIdArray = array();
// dd($hashtagArray);
$count = 0;
$decodedInstagramDataApiResponse = null;
if (isset($hashtagArray)) {
$userIGAccounts = Event_Social_Post::where('event_id', $this->event->id)->where('platform', 'instagram')->get();
if ($userIGAccounts != null) {
foreach ($userIGAccounts as $userinstaAcc) {
try {
$userInstaAccId = $userinstaAcc->page_id;
$instagramUserDataApi = $client->request('GET', "https://graph.facebook.com/v12.0/$userInstaAccId?fields=username%2Cprofile_picture_url&access_token=$token");
$getInstagramDataApiResponse = $instagramUserDataApi->getBody()->getContents();
$decodedInstagramDataApiResponse[] = json_decode($getInstagramDataApiResponse, true);
foreach ($hashtagArray as $key => $hashtagValue) {
if (isset($hashtagValue) && $hashtagValue != "") {
try {
$hashtagValue = ltrim($hashtagValue);
$InstagramHashtagIdApi = $client->request('GET', "https://graph.facebook.com/v11.0/ig_hashtag_search?user_id=$userInstaAccId&q=$hashtagValue&access_token=$token");
$getInstagramHashTagApiResponse = $InstagramHashtagIdApi->getBody()->getContents();
$decodedInstagramHashTag = json_decode($getInstagramHashTagApiResponse, true);
$InstagramHashtagID = $decodedInstagramHashTag['data'][0]['id'];
$hashtagPostSearchApi = $client->request('GET', "https://graph.facebook.com/v11.0/$InstagramHashtagID/recent_media?user_id=$userInstaAccId&fields=id%2Crecent_type%2Ccomments_count%2Clike_count%2Ccaption%2Cmedia_url%2Cpermalink%2Cchildren{media_url}%2Ctimestamp&access_token=$token");
$getHashtagPostSearchApiApiResponse = $hashtagPostSearchApi->getBody()->getContents();
$decodedHashtagPostSearchResponse = json_decode($getHashtagPostSearchApiApiResponse, true);
$hashtagIdArray[] = $decodedHashtagPostSearchResponse;
// var_dump($hashtagIdArray);
$count++;
} catch (ClientException $e) {
$response = $e->getResponse();
$responseBodyAsString = $response->getBody()->getContents();
if (Auth::check()) {
Session::put('instagramException', 'true');
Session::put('instagramExceptionMessage', $responseBodyAsString);
}
continue;
}
}
}
} catch (ClientException $e) {
$response = $e->getResponse();
$responseBodyAsString = $response->getBody()->getContents();
if (Auth::check()) {
Session::put('instagramException', 'true');
Session::put('instagramExceptionMessage', $responseBodyAsString);
}
continue;
}
}
if (count($hashtagIdArray) > 0) {
foreach ($hashtagIdArray as $key => $post) {
$userDataLoopIndex = 0;
if (count($post['data']) > 0) {
// dd($post['data']);
foreach ($post['data'] as $postDatum) {
if (isset($postDatum['children'])) {
foreach ($postDatum['children'] as $key => $childrenData) {
foreach ($childrenData as $childrenSingleton) {
// $childrenSingleton['media_url'];
$soc = new E_social_wall;
$soc->text = $postDatum['caption'] ?? ''; //->caption;
$soc->image = $childrenSingleton['media_url'] ?? ''; //->media_url;
$soc->platform = 'instagram';
if ($userDataLoopIndex < count($decodedInstagramDataApiResponse)) {
//dd($media['userData']);
if (isset($decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'])) {
$soc->user_img = $decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'];
} else {
$soc->user_img = 'https://www.kindpng.com/picc/m/22-223930_avatar-person-neutral-man-blank-face-buddy-facebook.png';
}
$soc->username = $decodedInstagramDataApiResponse[$userDataLoopIndex]['username'] ?? 'anonymous';
$userDataLoopIndex++;
} else if ($userDataLoopIndex >= count($decodedInstagramDataApiResponse)) {
$userDataLoopIndex = 0;
if (isset($decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'])) {
$soc->user_img = $decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'];
} else {
$soc->user_img = 'https://www.kindpng.com/picc/m/22-223930_avatar-person-neutral-man-blank-face-buddy-facebook.png';
}
$soc->username = $decodedInstagramDataApiResponse[$userDataLoopIndex]['username'] ?? 'anonymous';
$userDataLoopIndex++;
}
$soc->posted_at = date('Y-m-d h:i', strtotime($postDatum['timestamp']));
$soc->url = $childrenSingleton['media_url'] ?? ''; //->media_url;
$soc->event_id = $this->event->id;
$soc->is_hashtag = 1;
if ($soc->image != '' || $soc->url != '') {
$soc->save();
}
$count++;
}
}
} else {
$soc = new E_social_wall;
$soc->text = $postDatum['caption'] ?? ''; //->caption;
$soc->image = $postDatum['media_url'] ?? ''; //->media_url;
$soc->platform = 'instagram';
if ($userDataLoopIndex < count($decodedInstagramDataApiResponse)) {
//dd($media['userData']);
if (isset($decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'])) {
$soc->user_img = $decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'];
} else {
$soc->user_img = 'https://www.kindpng.com/picc/m/22-223930_avatar-person-neutral-man-blank-face-buddy-facebook.png';
}
$soc->username = $decodedInstagramDataApiResponse[$userDataLoopIndex]['username'] ?? 'anonymous';
$userDataLoopIndex++;
} else if ($userDataLoopIndex >= count($decodedInstagramDataApiResponse)) {
$userDataLoopIndex = 0;
if (isset($decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'])) {
$soc->user_img = $decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'];
} else {
$soc->user_img = 'https://www.kindpng.com/picc/m/22-223930_avatar-person-neutral-man-blank-face-buddy-facebook.png';
}
$soc->username = $decodedInstagramDataApiResponse[$userDataLoopIndex]['username'] ?? 'anonymous';
$userDataLoopIndex++;
}
$soc->posted_at = date('Y-m-d h:i', strtotime($postDatum['timestamp']));
$soc->url = $postDatum['media_url'] ?? ''; //->media_url;
$soc->event_id = $this->event->id;
$soc->is_hashtag = 1;
if ($soc->image != '' || $soc->url != '') {
$soc->save();
}
$count++;
}
}
}
}
}
return array('response' => $hashtagIdArray, 'userData' => $decodedInstagramDataApiResponse);
}
}
}
any suggestion or help would be great. Thank you all in advance.
PHP Script written for SuiteCRM improting is supposed to loop through all files in the directory and import each to Database. Having a lot of trouble.
Script reads and works on the first file only then finishes when it should loop :(
Importing works fine and data is added the the database from first file.
function MemberImportJob()
{
try
{
$config = new Configurator();
$config->loadConfig();
$xmlDataDir = 'custom/wimporter/eidimport';
$directoryContent = scandir($xmlDataDir);
//foreach ($directoryContent as $itemFile)
foreach (glob($xmlDataDir) as $itemfile)
{
var_dump($itemfile);
if (is_dir($xmlDataDir . DIRECTORY_SEPARATOR . $itemFile)) continue;
if (strcasecmp(substr($itemFile, -4), ".csv") != 0) continue;
$oFile = fopen($xmlDataDir . DIRECTORY_SEPARATOR . $itemFile, 'r');
if ($oFile !== FALSE)
{
$header = NULL;
$data = Array();
while (($data[] = fgetcsv($oFile, 90000, ',')) !== FALSE) { }
fclose($oFile);
//combine into a nice associative array:
$arow=Array();
$fields = array_shift($data);
foreach ($data as $i=>$arow)
{
array_combine " . $i);
if (is_array($arow)) {
$data[$i] = array_combine($fields, $arow);}
}
unset($arow);
$num = count($data);
for ($row=0; $row < $num - 1; $row++)
{
$Member = BeanFactory::getBean("locte_Membership");
$Member=$Member->retrieve_by_string_fields(array('last_name' => $data[$row]["LAST NAME"], 'first_name' => $data[$row]["FIRST NAME"], 'lcl_affiliate_number' => $data[$row]["AFFILIATE"]));
$MemberID = $Member->id;
if (is_null($Member)) {
$Member = BeanFactory::newBean('locte_Membership');
$delta = fillPerson($data[$row], $Member, "FULL NAME");
if(count($delta))
{
$Member_id = $Member->save();
}
} else {
v
var_dump($Member->id);
$delta = fillFoundrecord($data[$row], $Member, "FULL NAME");
echo("record Updated!");
$Member_id = $Member->save();
}
unset($data[$row]);
}
}
return true;
}
} catch (Exception $e)
{
return false;
}
}
I have a situation showed in the PHP code below, and I want to make a recursive function called check_recursive().
I have made the check_recursive() function below, but I want a recursive function, if it is possible.
Thank You!
$menu = '[{"id":"3|case_studies","children":[{"id":"2|case_studies","children":[{"id":"1|custom_links","children":[{"id":"2|faqe"}]}]}]},{"id":"11|klientet","children":[{"id":"8|klientet","children":[{"id":"7|klientet"}]}]},{"id":"9|klientet","children":[{"id":"10|klientet"}]},{"id":"4|klientet"}]';
$old_menu = json_decode($menu, true);
$new_menu = $this->check_recursive($old_menu);
function check_recursive($old_menu)
{
$i = 0;
$new_menu = [];
foreach ($old_menu as $menu_item)
{
if($name = $this->check_menu($menu_item['id']))
{
$new_menu[$i]['id'] = $menu_item['id'] . '|' . $name;
if(isset($menu_item['children']))
{
$e = 0;
foreach ($menu_item['children'] as $menu_item)
{
if($name = $this->check_menu($menu_item['id']))
{
$new_menu[$i]['children'][$e]['id'] = $menu_item['id'] . '|' . $name;
if(isset($menu_item['children']))
{
$y = 0;
foreach ($menu_item['children'] as $menu_item)
{
if($name = $this->check_menu($menu_item['id']))
{
$new_menu[$i]['children'][$e]['children'][$y]['id'] = $menu_item['id'] . '|' . $name;
if(isset($menu_item['children']))
{
$a = 0;
foreach ($menu_item['children'] as $menu_item)
{
if($name = $this->check_menu($menu_item['id']))
{
$new_menu[$i]['children'][$e]['children'][$y]['children'][$a]['id'] = $menu_item['id'] . '|' . $name;
}
$a++;
}
}
}
$y++;
}
}
}
$e++;
}
}
}
$i++;
}
return $new_menu;
}
function check_menu($string){
//Check if string exists in database
if($string){
return 'String exists';
}
return false;
}
I came up with this :
$menu = '[{"id":"3|case_studies","children":[{"id":"2|case_studies","children":[{"id":"1|custom_links","children":[{"id":"2|faqe"}]}]}]},{"id":"11|klientet","children":[{"id":"8|klientet","children":[{"id":"7|klientet"}]}]},{"id":"9|klientet","children":[{"id":"10|klientet"}]},{"id":"4|klientet"}]';
$old_menu = json_decode($menu, true);
$new_menu = check_recursive($old_menu);
function check_recursive($old_menu)
{
$new_menu = array();
foreach ($old_menu as $item) {
$name = check_menu($item['id']);
if($name){
$new_item = array(
'id' => $item['id'] . '|' . $name,
);
if(isset($item['children'])){
$new_item['children'] = check_recursive($item['children']);
}
$new_menu[] = $new_item;
}
}
return $new_menu;
}
function check_menu($string)
{
//Check if string exists in database
if ($string) {
return 'String exists';
}
return false;
}
Let me know if it suits your needs.
I have a small problem:
I need to repeat this
do {
$QUERY = "/member?id=".$counter."&action=refresh";
$URL = $HTTP.$HTTPUSER.":".$HTTPPASS."#".$HTTPSERVER.":".$HTTPPORT.$QUERY;
$xml = file_get_contents($URL);
$data = new SimpleXMLElement($xml);
$test_ip = (string)$data->c1;
$dnsip = explode('<br>', $test_ip);
$ext_ip = strip_tags($dnsip[1]);
if ($ext_ip != "127.0.0.1" && $ext_ip != "localhost") {
$dns = strip_tags($dnsip[0]);
echo "$dns $ext_ip <br>";
}
$counter +=1;
} while (!empty($data));
as many times as there are values inside an array, so i tried to add this
$ports = array('2001','2002','2003');
foreach ($ports as $HTTPPORT) {
echo "$HTTPPORT<br>";
$counter = 1;
do {
$QUERY = "/member?id=".$counter."&action=refresh";
$URL = $HTTP.$HTTPUSER.":".$HTTPPASS."#".$HTTPSERVER.":".$HTTPPORT.$QUERY;
$xml = file_get_contents($URL);
$data = new SimpleXMLElement($xml);
$test_ip = (string)$data->c1;
$dnsip = explode('<br>', $test_ip);
$ext_ip = strip_tags($dnsip[1]);
if ($ext_ip != "127.0.0.1" && $ext_ip != "localhost") {
$dns = strip_tags($dnsip[0]);
echo "$dns $ext_ip <br>";
}
$counter +=1;
} while (!empty($data)); }
The problem is that it executes the script with only first port number (2001), and i can't discover why.
Any Ideas?
You could be getting an exception inside your 'do .. while' loop that is causing bother.
I have added a 'try .. catch' block and some 'echo' statements to ensure it always loops round all the 'ports' now. Changed 'catch' to mark $data as empty then continue.
here is tested code:
<?php
$ports = array('2001','2002','2003');
$counter = 0; // total count of documents
foreach($ports as $HTTPPORT) {
echo $HTTPPORT, ' start of process port loop<br/>';
try { // catch any error -- report it and loop round again
do {
$QUERY = "/member?id=".$counter."&action=refresh";
$URL = ''; // $HTTP.$HTTPUSER.":".$HTTPPASS."#".$HTTPSERVER.":".$HTTPPORT.$QUERY;
try {
$xml = file_get_contents($URL);
$data = new SimpleXMLElement($xml);
}
catch (Exception $e) { // ignore any errors
echo 'SimpleXMLElement : oops :', $e->getMessage(), '<br />';
$data = ''; // mark as empty
}
if (!empty($data)) { // process data
$test_ip = (string)$data->c1;
$dnsip = explode('<br>', $test_ip);
$ext_ip = strip_tags($dnsip[1]);
if ($ext_ip != "127.0.0.1" && $ext_ip != "localhost") {
$dns = strip_tags($dnsip[0]);
echo "$dns $ext_ip <br>";
}
}
$counter +=1;
} while (!empty($data));
} // end of try to get and process a document...
catch (Exception $e) { // catch all errors for now
echo 'Processing List of Ports: oops! :', $e->getMessage(), '<br />';
}
} // end of foreach port