Laravel Complex API Code Optimization to avoid nested loops - php

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.

Related

How to correctly write a foreach for $clientList in TS3AntiVPN application?

I download a TS3AntiVPN but it shoes an error. I use a Linux Server running Debian 9 Plesk installed.
PHP Warning: Invalid argument supplied for foreach() in
/var/www/vhosts/suspectgaming.de/tsweb.suspectgaming.de/antivpn/bot.php
on line 29
How do I solve this problem?
<?php
require("ts3admin.class.php");
$ignore_groups = array('1',); // now supports one input and array input
$msg_kick = "VPN";
$login_query = "serveradmin";
$pass_query = "";
$adres_ip = "94.249.254.216";
$query_port = "10011";
$port_ts = "9987";
$nom_bot = "AntiVPN";
$ts = new ts3Admin($adres_ip, $query_port);
if(!$ts->getElement('success', $ts->connect())) {
die("Anti-Proxy");
}
$ts->login($login_query, $pass_query);
$ts->selectServer($port_ts);
$ts->setName($nom_bot);
while(true) {
sleep(1);
$clientList = $ts->clientList("-ip -groups");
foreach($clientList['data'] as $val) {
$groups = explode(",", $val['client_servergroups'] );
if(is_array($ignore_groups)){
foreach($ignore_groups as $ig){
if(in_array($ig, $groups) || ($val['client_type'] == 1)) {
continue;
}
}
}else{
if(in_array($ignore_groups, $groups) || ($val['client_type'] == 1)) {
continue;
}
}
$file = file_get_contents('https://api.xdefcon.com/proxy/check/?ip='.$val['connection_client_ip'].'');
$file = json_decode($file, true);
if($file['message'] == "Proxy detected.") {
$ts->clientKick($val['clid'], "server", $msg_kick);
}
}
}
?>
You might be missing data in your first array. You may add an if statement to check if there is data in your $clientList['data'] var:
if (is_array($clientList['data'])) {
}
Or you might also check if sizeof(); of your array is larger than a number, you may desire.
if (is_array($clientList['data']) && sizeof($clientList['data']) > 0) {
}
Code
require "ts3admin.class.php";
$ignore_groups = array('1'); // now supports one input and array input
$msg_kick = "VPN";
$login_query = "serveradmin";
$pass_query = "";
$adres_ip = "94.249.254.216";
$query_port = "10011";
$port_ts = "9987";
$nom_bot = "AntiVPN";
$ts = new ts3Admin($adres_ip, $query_port);
if (!$ts->getElement('success', $ts->connect())) {
die("Anti-Proxy");
}
$ts->login($login_query, $pass_query);
$ts->selectServer($port_ts);
$ts->setName($nom_bot);
while (true) {
sleep(1);
$clientList = $ts->clientList("-ip -groups");
if (is_array($clientList['data']) && sizeof($clientList['data']) > 0) {
foreach ($clientList['data'] as $val) {
$groups = explode(",", $val['client_servergroups']);
if (is_array($ignore_groups)) {
foreach ($ignore_groups as $ig) {
if (in_array($ig, $groups) || ($val['client_type'] == 1)) {
continue;
}
}
} else {
if (in_array($ignore_groups, $groups) || ($val['client_type'] == 1)) {
continue;
}
}
$file = file_get_contents('https://api.xdefcon.com/proxy/check/?ip=' . $val['connection_client_ip'] . '');
$file = json_decode($file, true);
if ($file['message'] == "Proxy detected.") {
$ts->clientKick($val['clid'], "server", $msg_kick);
}
}
} else {
echo "There might be no data in Client List";
}
}

A database has already be specified for this key. multiple database

Hello world I'm new so sorry for my question. but I need your help
I have this code
public function GetSyncTransaksi ($ip_add_Get,$DBIDGet='db_ique',$table_get='transaksi') {
$temp_get = NULL;
if ($DBIDGet == 'db_ique') {
$dbhost_get = $ip_add_Get;
$dbuser_get = USER_CABANG; //Harus diganti
$dbpwd_get = PASS_CABANG; //Harus diganti
$dbname_get = $DBIDGet;
} else {
$dbhost_get = $ip_add_Get;
$dbuser_get = USER_PUSAT; //Harus diganti
$dbpwd_get = PASS_PUSAT; //Harus diganti
$dbname_get = "ique_".$DBIDGet;
}
R::addDatabase($dbname_get, 'mysql:host='.$dbhost_get.';dbname='.$dbname_get, $dbuser_get, $dbpwd_get, TRUE);
R::selectDatabase($dbname_get);
$qget = "SELECT * FROM sync_$table_get";
$temp_get = R::getAll($qget);
return $temp_get;
}
public function UpdateSyncTransaksi ($ip_add,$DBID='db_ique',$table='transaksi') {
$temp = NULL;
if ($DBID == 'db_ique') {
$dbhost = $ip_add;
$dbuser = USER_CABANG;
$dbpwd = PASS_CABANG;
$dbname = $DBID;
} else {
$dbhost = $ip_add;
$dbuser = USER_PUSAT;
$dbpwd = PASS_PUSAT;
$dbname = "ique_".$DBID;
}
R::addDatabase($dbname, 'mysql:host='.$dbhost.';dbname='.$dbname, $dbuser, $dbpwd, TRUE);
R::selectDatabase($dbname);
$q = "TRUNCATE TABLE sync_$table";
$temp = R::exec($q);
$q = "INSERT INTO sync_$table SELECT tanggal,COUNT(*) FROM $table GROUP BY tanggal";
$temp = R::exec($q);
return $temp;
}
And I call to this Function
public function CompareSyncTransaksi ($server,$id,$table='transaksi') {
$difference = NULL;
$updatesynccabang = $this->UpdateSyncTransaksi($server,'db_ique',$table); //Update sync_transaksi cabang
$updatesyncpusat = $this->UpdateSyncTransaksi("localhost",$id,$table); //Update sync_transaksi pusat
$synccabang = $this->GetSyncTransaksi($server,'db_ique',$table);
$syncpusat = $this->GetSyncTransaksi("localhost",$id,$table);
$tglcabang = NULL;
if ($synccabang != NULL) {
foreach ($synccabang as $temp) {
$tglcabang[] = $temp->tanggal;
}
}
$tglpusat = NULL;
if ($syncpusat != NULL) {
foreach ($syncpusat as $temp) {
$tglpusat[] = $temp->tanggal;
}
}
$intersect = NULL;
if($tglcabang != NULL && $tglpusat != NULL) {
$difference = array_diff($tglcabang,$tglpusat);
$intersect = array_intersect($tglcabang,$tglpusat);
}
if($intersect != NULL) {
foreach ($intersect as $temp) {
foreach ($synccabang as $temp1) {
if ($temp1->tanggal == $temp) {
$jumlahcabang = $temp1->jumlah;
}
}
foreach ($syncpusat as $temp2) {
if ($temp2->tanggal == $temp) {
$jumlahpusat = $temp2->jumlah;
}
}
if ($jumlahcabang != $jumlahpusat) {
$difference[] = $temp;
}
}
}
if ($difference) {
asort($difference);
}
return $difference;
}
The problem is I got Error "A database has already be specified for this key."
I think the problem is in function GetSyncTransaksi and function UpdateSyncTransaksi.
How can I fix this. please help thank you

Adding a 0 at the end of the input when it is less than 9 digits

I have an e-commerce site in opencart and I have a problem in the RG field which is as follows, when the user registers it fills all the fields normally but in the RG field there are those users that have one digit less in the RG that they are usually 9 more digits have users with 8 and they usually register on the site more when they are going to make a purchase they can not conclude it because the RG is with a number less would like to know if it is possible to put a code that does the following when the User to enter a RG with one digit less or less than 9 add a 0 at the end of the field so that it is complete.
This is uexatamente the input that I need to change so that when the user clicks on register it will be saved with the longest digit
<Input type = "text" name = "custom_field [account] [2]" value = "" placeholder = "RG" id = "input-custom-field2" class = "form-control">
I do not know if this is where I am going to implement my code but this is one of the controllers responsible for the registration of the form
<?php
class ControllerAccountRegister extends Controller {
private $error = array();
public function index() {
if ($this->customer->isLogged()) {
$this->response->redirect($this->url->link('account/account', '', 'SSL'));
}
$this->load->language('account/register');
$this->document->setTitle($this->language->get('heading_title'));
$this->document->addScript('catalog/view/javascript/jquery/datetimepicker/moment.js');
$this->document->addScript('catalog/view/javascript/jquery/datetimepicker/bootstrap-datetimepicker.min.js');
$this->document->addStyle('catalog/view/javascript/jquery/datetimepicker/bootstrap-datetimepicker.min.css');
$this->load->model('account/customer');
if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
$customer_id = $this->model_account_customer->addCustomer($this->request->post);
// Clear any previous login attempts for unregistered accounts.
$this->model_account_customer->deleteLoginAttempts($this->request->post['email']);
$this->customer->login($this->request->post['email'], $this->request->post['password']);
unset($this->session->data['guest']);
// Add to activity log
$this->load->model('account/activity');
$activity_data = array(
'customer_id' => $customer_id,
'name' => $this->request->post['firstname']
//'name' => $this->request->post['firstname'] . ' ' . $this->request->post['lastname']
);
$this->model_account_activity->addActivity('register', $activity_data);
$this->response->redirect($this->url->link('account/success'));
}
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/home')
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_account'),
'href' => $this->url->link('account/account', '', 'SSL')
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_register'),
'href' => $this->url->link('account/register', '', 'SSL')
);
$data['heading_title'] = $this->language->get('heading_title');
$data['text_account_already'] = sprintf($this->language->get('text_account_already'), $this->url->link('account/login', '', 'SSL'));
$data['text_your_details'] = $this->language->get('text_your_details');
$data['text_your_address'] = $this->language->get('text_your_address');
$data['text_your_password'] = $this->language->get('text_your_password');
$data['text_newsletter'] = $this->language->get('text_newsletter');
$data['text_yes'] = $this->language->get('text_yes');
$data['text_no'] = $this->language->get('text_no');
$data['text_select'] = $this->language->get('text_select');
$data['text_none'] = $this->language->get('text_none');
$data['text_loading'] = $this->language->get('text_loading');
$data['entry_customer_group'] = $this->language->get('entry_customer_group');
$data['entry_firstname'] = $this->language->get('entry_firstname');
// $data['entry_lastname'] = $this->language->get('entry_lastname');
$data['entry_email'] = $this->language->get('entry_email');
$data['entry_telephone'] = $this->language->get('entry_telephone');
$data['entry_fax'] = $this->language->get('entry_fax');
$data['entry_company'] = $this->language->get('entry_company');
$data['entry_address_1'] = $this->language->get('entry_address_1');
$data['entry_address_2'] = $this->language->get('entry_address_2');
$data['entry_postcode'] = $this->language->get('entry_postcode');
$data['entry_city'] = $this->language->get('entry_city');
$data['entry_country'] = $this->language->get('entry_country');
$data['entry_zone'] = $this->language->get('entry_zone');
$data['entry_newsletter'] = $this->language->get('entry_newsletter');
$data['entry_password'] = $this->language->get('entry_password');
$data['entry_confirm'] = $this->language->get('entry_confirm');
$data['button_continue'] = $this->language->get('button_continue');
$data['button_upload'] = $this->language->get('button_upload');
if (isset($this->error['warning'])) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
if (isset($this->error['firstname'])) {
$data['error_firstname'] = $this->error['firstname'];
} else {
$data['error_firstname'] = '';
}
// if (isset($this->error['lastname'])) {
// $data['error_lastname'] = $this->error['lastname'];
// } else {
// $data['error_lastname'] = '';
// }
if (isset($this->error['email'])) {
$data['error_email'] = $this->error['email'];
} else {
$data['error_email'] = '';
}
if (isset($this->error['telephone'])) {
$data['error_telephone'] = $this->error['telephone'];
} else {
$data['error_telephone'] = '';
}
if (isset($this->error['address_1'])) {
$data['error_address_1'] = $this->error['address_1'];
} else {
$data['error_address_1'] = '';
}
if (isset($this->error['city'])) {
$data['error_city'] = $this->error['city'];
} else {
$data['error_city'] = '';
}
if (isset($this->error['postcode'])) {
$data['error_postcode'] = $this->error['postcode'];
} else {
$data['error_postcode'] = '';
}
if (isset($this->error['country'])) {
$data['error_country'] = $this->error['country'];
} else {
$data['error_country'] = '';
}
if (isset($this->error['zone'])) {
$data['error_zone'] = $this->error['zone'];
} else {
$data['error_zone'] = '';
}
if (isset($this->error['custom_field'])) {
$data['error_custom_field'] = $this->error['custom_field'];
} else {
$data['error_custom_field'] = array();
}
if (isset($this->error['password'])) {
$data['error_password'] = $this->error['password'];
} else {
$data['error_password'] = '';
}
if (isset($this->error['confirm'])) {
$data['error_confirm'] = $this->error['confirm'];
} else {
$data['error_confirm'] = '';
}
$data['action'] = $this->url->link('account/register', '', 'SSL');
$data['customer_groups'] = array();
if (is_array($this->config->get('config_customer_group_display'))) {
$this->load->model('account/customer_group');
$customer_groups = $this->model_account_customer_group->getCustomerGroups();
foreach ($customer_groups as $customer_group) {
if (in_array($customer_group['customer_group_id'], $this->config->get('config_customer_group_display'))) {
$data['customer_groups'][] = $customer_group;
}
}
}
if (isset($this->request->post['customer_group_id'])) {
$data['customer_group_id'] = $this->request->post['customer_group_id'];
} else {
$data['customer_group_id'] = $this->config->get('config_customer_group_id');
}
if (isset($this->request->post['firstname'])) {
$data['firstname'] = $this->request->post['firstname'];
} else {
$data['firstname'] = '';
}
// if (isset($this->request->post['lastname'])) {
// $data['lastname'] = $this->request->post['lastname'];
// } else {
// $data['lastname'] = '';
// }
if (isset($this->request->post['email'])) {
$data['email'] = $this->request->post['email'];
} else {
$data['email'] = '';
}
if (isset($this->request->post['telephone'])) {
$data['telephone'] = $this->request->post['telephone'];
} else {
$data['telephone'] = '';
}
if (isset($this->request->post['fax'])) {
$data['fax'] = $this->request->post['fax'];
} else {
$data['fax'] = '';
}
if (isset($this->request->post['company'])) {
$data['company'] = $this->request->post['company'];
} else {
$data['company'] = '';
}
if (isset($this->request->post['address_1'])) {
$data['address_1'] = $this->request->post['address_1'];
} else {
$data['address_1'] = '';
}
if (isset($this->request->post['address_2'])) {
$data['address_2'] = $this->request->post['address_2'];
} else {
$data['address_2'] = '';
}
if (isset($this->request->post['postcode'])) {
$data['postcode'] = $this->request->post['postcode'];
} elseif (isset($this->session->data['shipping_address']['postcode'])) {
$data['postcode'] = $this->session->data['shipping_address']['postcode'];
} else {
$data['postcode'] = '';
}
if (isset($this->request->post['city'])) {
$data['city'] = $this->request->post['city'];
} else {
$data['city'] = '';
}
if (isset($this->request->post['country_id'])) {
$data['country_id'] = $this->request->post['country_id'];
} elseif (isset($this->session->data['shipping_address']['country_id'])) {
$data['country_id'] = $this->session->data['shipping_address']['country_id'];
} else {
$data['country_id'] = $this->config->get('config_country_id');
}
if (isset($this->request->post['zone_id'])) {
$data['zone_id'] = $this->request->post['zone_id'];
} elseif (isset($this->session->data['shipping_address']['zone_id'])) {
$data['zone_id'] = $this->session->data['shipping_address']['zone_id'];
} else {
$data['zone_id'] = '';
}
$this->load->model('localisation/country');
$data['countries'] = $this->model_localisation_country->getCountries();
// Custom Fields
$this->load->model('account/custom_field');
$data['custom_fields'] = $this->model_account_custom_field->getCustomFields();
if (isset($this->request->post['custom_field'])) {
if (isset($this->request->post['custom_field']['account'])) {
$account_custom_field = $this->request->post['custom_field']['account'];
} else {
$account_custom_field = array();
}
if (isset($this->request->post['custom_field']['address'])) {
$address_custom_field = $this->request->post['custom_field']['address'];
} else {
$address_custom_field = array();
}
$data['register_custom_field'] = $account_custom_field + $address_custom_field;
} else {
$data['register_custom_field'] = array();
}
if (isset($this->request->post['password'])) {
$data['password'] = $this->request->post['password'];
} else {
$data['password'] = '';
}
if (isset($this->request->post['confirm'])) {
$data['confirm'] = $this->request->post['confirm'];
} else {
$data['confirm'] = '';
}
if (isset($this->request->post['newsletter'])) {
$data['newsletter'] = $this->request->post['newsletter'];
} else {
$data['newsletter'] = '';
}
if ($this->config->get('config_account_id')) {
$this->load->model('catalog/information');
$information_info = $this->model_catalog_information->getInformation($this->config->get('config_account_id'));
if ($information_info) {
$data['text_agree'] = sprintf($this->language->get('text_agree'), $this->url->link('information/information/agree', 'information_id=' . $this->config->get('config_account_id'), 'SSL'), $information_info['title'], $information_info['title']);
} else {
$data['text_agree'] = '';
}
} else {
$data['text_agree'] = '';
}
if (isset($this->request->post['agree'])) {
$data['agree'] = $this->request->post['agree'];
} else {
$data['agree'] = false;
}
$data['column_left'] = $this->load->controller('common/column_left');
$data['column_right'] = $this->load->controller('common/column_right');
$data['content_top'] = $this->load->controller('common/content_top');
$data['content_bottom'] = $this->load->controller('common/content_bottom');
$data['footer'] = $this->load->controller('common/footer');
$data['header'] = $this->load->controller('common/header');
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/account/register.tpl')) {
$this->response->setOutput($this->load->view($this->config->get('config_template') . '/template/account/register.tpl', $data));
} else {
$this->response->setOutput($this->load->view('default/template/account/register.tpl', $data));
}
}
public function validate() {
if ((utf8_strlen(trim($this->request->post['firstname'])) < 1) || (utf8_strlen(trim($this->request->post['firstname'])) > 32)) {
$this->error['firstname'] = $this->language->get('error_firstname');
}
// if ((utf8_strlen(trim($this->request->post['lastname'])) < 1) || (utf8_strlen(trim($this->request->post['lastname'])) > 32)) {
// $this->error['lastname'] = $this->language->get('error_lastname');
// }
if ((utf8_strlen($this->request->post['email']) > 96) || !preg_match('/^[^\#]+#.*.[a-z]{2,15}$/i', $this->request->post['email'])) {
$this->error['email'] = $this->language->get('error_email');
}
if ($this->model_account_customer->getTotalCustomersByEmail($this->request->post['email'])) {
$this->error['warning'] = $this->language->get('error_exists');
}
if ((utf8_strlen($this->request->post['telephone']) < 3) || (utf8_strlen($this->request->post['telephone']) > 32)) {
$this->error['telephone'] = $this->language->get('error_telephone');
}
if ((utf8_strlen(trim($this->request->post['address_1'])) < 3) || (utf8_strlen(trim($this->request->post['address_1'])) > 128)) {
$this->error['address_1'] = $this->language->get('error_address_1');
}
if ((utf8_strlen(trim($this->request->post['city'])) < 2) || (utf8_strlen(trim($this->request->post['city'])) > 128)) {
$this->error['city'] = $this->language->get('error_city');
}
$this->load->model('localisation/country');
$country_info = $this->model_localisation_country->getCountry($this->request->post['country_id']);
if ($country_info && $country_info['postcode_required'] && (utf8_strlen(trim($this->request->post['postcode'])) < 2 || utf8_strlen(trim($this->request->post['postcode'])) > 10)) {
$this->error['postcode'] = $this->language->get('error_postcode');
}
if ($this->request->post['country_id'] == '') {
$this->error['country'] = $this->language->get('error_country');
}
if (!isset($this->request->post['zone_id']) || $this->request->post['zone_id'] == '') {
$this->error['zone'] = $this->language->get('error_zone');
}
// Customer Group
if (isset($this->request->post['customer_group_id']) && is_array($this->config->get('config_customer_group_display')) && in_array($this->request->post['customer_group_id'], $this->config->get('config_customer_group_display'))) {
$customer_group_id = $this->request->post['customer_group_id'];
} else {
$customer_group_id = $this->config->get('config_customer_group_id');
}
// Custom field validation
$this->load->model('account/custom_field');
$custom_fields = $this->model_account_custom_field->getCustomFields($customer_group_id);
foreach ($custom_fields as $custom_field) {
if ($custom_field['required'] && empty($this->request->post['custom_field'][$custom_field['location']][$custom_field['custom_field_id']])) {
$this->error['custom_field'][$custom_field['custom_field_id']] = sprintf($this->language->get('error_custom_field'), $custom_field['name']);
}
}
if ((utf8_strlen($this->request->post['password']) < 4) || (utf8_strlen($this->request->post['password']) > 20)) {
$this->error['password'] = $this->language->get('error_password');
}
if ($this->request->post['confirm'] != $this->request->post['password']) {
$this->error['confirm'] = $this->language->get('error_confirm');
}
// Agree to terms
if ($this->config->get('config_account_id')) {
$this->load->model('catalog/information');
$information_info = $this->model_catalog_information->getInformation($this->config->get('config_account_id'));
if ($information_info && !isset($this->request->post['agree'])) {
$this->error['warning'] = sprintf($this->language->get('error_agree'), $information_info['title']);
}
}
return !$this->error;
}
public function customfield() {
$json = array();
$this->load->model('account/custom_field');
// Customer Group
if (isset($this->request->get['customer_group_id']) && is_array($this->config->get('config_customer_group_display')) && in_array($this->request->get['customer_group_id'], $this->config->get('config_customer_group_display'))) {
$customer_group_id = $this->request->get['customer_group_id'];
} else {
$customer_group_id = $this->config->get('config_customer_group_id');
}
$custom_fields = $this->model_account_custom_field->getCustomFields($customer_group_id);
foreach ($custom_fields as $custom_field) {
$json[] = array(
'custom_field_id' => $custom_field['custom_field_id'],
'required' => $custom_field['required']
);
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
}
may be you can use this script.
function putZeroToLastItem($text) {
$length = strlen($text);
if( $length < 9 ) {
$text .= '0'
}
return $text
}
I hope , this script will solve your porblem.
<?php
$num = 3;
$num_padded = sprintf("%02d", $num);
echo $num_padded; // returns 03
?>
Try this simple snippet
You want to add 0 after the number (9 digit)? Use jquery if you want it in client side.
function addZero (data){
return data+(data <10 ? '0':'');
}
var num =$('#number').val();
var nNum = addZero(num);
Hope it helps.
A reduced way of #mehfatitem:
function putZeroToLastItem($text) {
return (strlen($text) < 9) ? $text . '0' : $text;
}

how can i create and pass value in multidimensional array in php?

I need to save some data's in php. I am trying this code
$click_free = [];
$ano = 0;
while($res_qry = mysql_fetch_array($sel_qry)){
$arr_cnt = sizeof($click_free);
if($arr_cnt != 0){
$m = 0;
for($k=0;$k<$arr_cnt;$k++)
{
if($click_free[$k][0] == $res_qry['Free_id'])
{
$click_free[$k][0] = ($click_free[$k][0]+$res_qry['Qty']);
$m=1;
}
}if($m==0){
$click_free[$arr_cnt] = [1,];
}
}else{
$click_free[0] = [$res_qry['Free_id'],$res_qry['Qty']];
}
}
But this code has many error. Please help me solve this
while($res_qry = mysql_fetch_array($sel_qry)){
$id_existed = false;
if(!empty($click_free))
foreach($click_free as $key=>$ligne)
if( $ligne[0] == $res_qry['Free_id']){
$qty = $ligne[1] + $res_qry['Qty'];
$click_free[$key] = [ $ligne[0] , $qty ];
$id_existed =true;
}
if(!$id_existed){
$click_free[] = [ $res_qry['Free_id'] , $res_qry['Qty'] ];
}
}
Finally we got a solution
while($res_qry = mysql_fetch_array($sel_qry)){
$arr_cnt = sizeof($click_free);
if($arr_cnt != 0){
$m = 0;
foreach ($click_free as $k => $v) {
if ($v['Free_id']==$res_qry['Free_id']) {
S_qty=$v['Qty']+$res_qry['Qty'];
$click_free[$k]['Qty']=$S_qty;
$m=1;
}
}
if($m==0){
$click_free[] = array("Free_id" => $res_qry['Free_id'],"Qty"=>$res_qry['Qty']);
}
}else{
$click_free[] = array("Free_id" => $res_qry['Free_id'],"Qty"=>$res_qry['Qty']);
}
}
Thanks to bfahmi, Kris Roofe, B. Desai , user3542450, dr_debug

Pass $sSymbol an input parameter to a Class

I got this class code from https://github.com/ricardotiago/sec-gov-api, which is used to retrieve and parse quarterly and yearly reports from the U.S Securities Exchange website.I do not understand how to print the results and what sort of parameters it's accepts. Is$sSmbol an input parameter, how do I pass this parameter so that it displays the quarterly and yearly report
<?php
require_once "parallelCurl.php";
class SecGovAPI {
const SEARCH_LINK = "http://www.sec.gov/cgi-bin/browse-edgar";
const BASE_LINK = "http://www.sec.gov/";
const QUARTERLY_REPORT = '10-Q';
const YEARLY_REPORT = '10-K';
const MOST_RECENT_REPORT = 0;
const ALL_REPORTS = 1;
public function __construct($sSymbol) {
$this->oParallelCurl = new ParallelCurl();
$this->sSymbol = $sSymbol;
$this->oDoc = new DOMDocument();
$this->report = array();
}
public function getQuaterlyReport($iSearchType = SecGovAPI::MOST_RECENT_REPORT) {
if ($iSearchType !== SecGovAPI::MOST_RECENT_REPORT && $iSearchType !== SecGovAPI::ALL_REPORTS) {
return array();
}
$aReportLinks = $this->search(SecGovAPI::QUARTERLY_REPORT, $iSearchType);
var_dump($aReportLinks);
foreach ($aReportLinks as $link) {
$this->oParallelCurl->addUrl(SecGovAPI::BASE_LINK."/".$link);
}
$aData = $this->oParallelCurl->run();
foreach ($aData as $link => $xml) {
$this->oDoc->loadXML($xml);
$oXPath = new DOMXPath($this->oDoc);
$oXPath->registerNamespace("xbrli", "http://www.xbrl.org/2003/instance");
$this->getReportData($oXPath, $link, "dei:EntityCommonStockSharesOutstanding", "CommonStockSharesOutstanding");
$this->getReportData($oXPath, $link, "us-gaap:NetIncomeLoss", "NetIncomeLoss");
}
var_dump($this->report);
}
public function getYearlyReport($iSearchType = SecGovAPI::MOST_RECENT_REPORT) {
if ($iSearchType !== SecGovAPI::MOST_RECENT_REPORT && $iSearchType !== SecGovAPI::ALL_REPORTS) {
return array();
}
$aReportLinks = $this->search(SecGovAPI::YEARLY_REPORT, $iSearchType);
var_dump($aReportLinks);
foreach ($aReportLinks as $link) {
$this->oParallelCurl->addUrl(SecGovAPI::BASE_LINK."/".$link);
}
$aData = $this->oParallelCurl->run();
foreach ($aData as $link => $xml) {
$this->oDoc->loadXML($xml);
$oXPath = new DOMXPath($this->oDoc);
$oXPath->registerNamespace("xbrli", "http://www.xbrl.org/2003/instance");
$this->getReportData($oXPath, $link, "dei:EntityCommonStockSharesOutstanding", "CommonStockSharesOutstanding");
$this->getReportData($oXPath, $link, "us-gaap:NetIncomeLoss", "NetIncomeLoss");
}
var_dump($this->report);
}
public function getReportData($oXPath, $link, $sEntity, $sSaveAs) {
$oNodelist = $oXPath->query("//xbrli:xbrl/".$sEntity);
for ($i = 0; $i < $oNodelist->length; $i++) {
$this->report[$link][$sSaveAs][$i] = $oNodelist->item($i)->nodeValue;
}
}
protected function search($sType, $iSearchType) {
$aParams = array("company" => "",
"match" => "",
"CIK" => $this->sSymbol,
"filenum" => "",
"State" => "",
"Country" => "",
"SIC" => "",
"count" => "40",
"owner" => "exclude",
"Find" => "Find Companies",
"action" => "getcompany",
"type" => $sType,
"output" => "atom");
$sUrl = SecGovAPI::SEARCH_LINK . "?". http_build_query($aParams);
$this->oDoc->load($sUrl);
$oXPath = new DOMXPath($this->oDoc);
$oXPath->registerNamespace("atom", "http://www.w3.org/2005/Atom");
$aLinks = $this->getReportLinks($oXPath, $iSearchType);
$aReportLinks = array();
foreach ($aLinks as $link) {
$this->oParallelCurl->addUrl($link);
}
$aHtmls = $this->oParallelCurl->run();
foreach ($aHtmls as $html) {
$this->oDoc->loadHTML($html);
$oXPath = new DOMXPath($this->oDoc);
$oNodeList = $oXPath->query('//table[#summary="Data Files"]/tr[2]/td[3]/a');
if ($oNodeList->length === 0) continue;
$aReportLinks[] = $oNodeList->item(0)->getAttribute("href");
}
return $aReportLinks;
}
protected function getReportLinks($oXPath, $iSearchType) {
if ($iSearchType === SecGovAPI::MOST_RECENT_REPORT) {
$aNodeList = $oXPath->query("//atom:feed/atom:entry[1]/atom:link");
if ($aNodeList->length === 1)
return array($aNodeList->item(0)->getAttribute("href"));
else
return null;
}
else if ($iSearchType === SecGovAPI::ALL_REPORTS) {
$aNodeList = $oXPath->query("//atom:feed/atom:entry/atom:link");
for ($i = 0; $i < $aNodeList->length; $i++) {
$aReportLinks[] = $aNodeList->item($i)->getAttribute("href");
}
return $aReportLinks;
}
else return null;
}
protected function getAccessionNumber($oXPath, $iSearchType) {
if ($iSearchType === SecGovAPI::MOST_RECENT_REPORT) {
$aNodeList = $oXPath->query("//atom:feed/atom:entry[1]/atom:id");
if ($aNodeList->length === 1) $sRawAccessNumber = $aNodeList->item(0)->nodeValue;
else return null;
return $this->processAccessionNumber($sRawAccessNumber);
}
else if ($iSearchType === SecGovAPI::ALL_REPORTS) {
$aNodeList = $oXPath->query("//atom:feed/atom:entry/atom:id");
for ($i = 0; $i < $aNodeList->length; $i++) {
$sRawAccessNumber = $aNodeList->item($i)->nodeValue;
$aAccessionNumber[] = $this->processAccessionNumber($sRawAccessNumber);
}
return $aAccessionNumber;
}
else return null;
}
protected function processAccessionNumber($sRawAccessNumber) {
$aSplitData = preg_split('/accession-number=/', $sRawAccessNumber);
if (!isset($aSplitData[1])) return null;
$sAccessionNumber = str_replace('-','', $aSplitData[1]);
return $sAccessionNumber;
}
protected function getReportDate($oXPath, $iSearchType) {
if ($iSearchType === SecGovAPI::MOST_RECENT_REPORT) {
$aNodeList = $oXPath->query("//atom:feed/atom:entry[1]/atom:updated");
if ($aNodeList->length === 1)
return $sUpdated = $aNodeList->item(0)->nodeValue;
else
return null;
}
else if ($iSearchType === SecGovAPI::ALL_REPORTS) {
$aNodeList = $oXPath->query("//atom:feed/atom:entry/atom:updated");
for ($i = 0; $i < $aNodeList->length; $i++) {
$aUpdated[] = $aNodeList->item($i)->nodeValue;
}
return $aUpdated;
}
else return null;
}
}
?>
parallelCurl.php
<?php
class ParallelCurl {
protected $aHandlers;
public function __construct() {
$this->aHandlers = array();
$this->rMultiHandler = curl_multi_init();
}
public function addUrl($sUrl) {
$rHandler = curl_init();
curl_setopt($rHandler, CURLOPT_URL, $sUrl);
curl_setopt($rHandler, CURLOPT_HEADER, 0);
curl_setopt($rHandler, CURLOPT_RETURNTRANSFER, 1);
curl_multi_add_handle($this->rMultiHandler, $rHandler);
$this->aHandlers[$sUrl] = $rHandler;
}
public function run() {
$blsRunning = null;
do {
$rHandler = curl_multi_exec($this->rMultiHandler, $blsRunning);
} while ($rHandler === CURLM_CALL_MULTI_PERFORM);
while ($blsRunning && $rHandler == CURLM_OK) {
if (curl_multi_select($this->rMultiHandler) != -1) {
do {
$rHandler = curl_multi_exec($this->rMultiHandler, $blsRunning);
} while ($rHandler == CURLM_CALL_MULTI_PERFORM);
}
}
foreach ($this->aHandlers as $url => $handler) {
$data[$url] = curl_multi_getcontent($handler);
curl_multi_remove_handle($this->rMultiHandler, $handler);
}
$this->aHandlers = array();
return $data;
}
public function __destruct() {
curl_multi_close($this->rMultiHandler);
}
}
?>
To create an instance of the SecGovAPI class you can use the new keyword:
$class = new SecGovAPI($sSymbol);
then you can call the methods getQuaterlyReport and getYearlyReport with:
echo $class->getQuaterlyReport();
echo $class->getYearlyReport();
Both these methods has an argument, and by default is SecGovAPI::MOST_RECENT_REPORT. You can also use:
SecGovAPI::QUARTERLY_REPORT
SecGovAPI::YEARLY_REPORT
SecGovAPI::ALL_REPORTS
Example:
echo $class->getQuaterlyReport(SecGovAPI::QUARTERLY_REPORT);

Categories