how can i create and pass value in multidimensional array in php? - 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

Related

Laravel Complex API Code Optimization to avoid nested loops

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.

Does not display the result of parsing

Good afternoon, please help me. At me when parsing the result of parsing is not displayed.
link my php file https://dropmefiles.com/cv4Q2
Please correct where I was wrong. Or help to rewrite a little code so that it displays the result of the parser.
Already tried all the options, it does not work in any way. My knowledge here is not enough.
1 file
part 1
function getForecastXML($cid='579432') {
$cid = "579432";
$hoffset = "4";
$appid= "d86ad74d22ce9cc528d8baee65acd408";
$lang= "ru";
$days = array();
$xml = #file_get_contents("http://api.openweathermap.org/data/2.5/forecast?id=$cid&mode=xml&appid=$appid&lang=$lang&type=like");
if ($xml===false) { return;} else {
$xml = simplexml_load_string($xml);
$cityname = (string)$xml->location->name;
$weekdays[0] = "Воскресенье";
$weekdays[1] = "Понедельник";
$weekdays[2] = "Вторник";
$weekdays[3] = "Среда";
$weekdays[4] = "Четверг";
$weekdays[5] = "Пятница";
$weekdays[6] = "Суббота";
if (count($xml->forecast->time)>0){
foreach ($xml->forecast->time as $fpart) {
$forecast = array();
$attr = $fpart->attributes();
$forecast['t']['min'] = (string)round(($fpart->temperature->attributes()->min)-273,15,PHP_ROUND_HALF_UP);
$forecast['t']['min'] = $forecast['t']['min'] > 0 ? "+".$forecast['t']['min'] : $forecast['t']['min'];
$forecast['t']['max'] = (string)round(($fpart->temperature->attributes()->max)-273,15,PHP_ROUND_HALF_UP);
$forecast['t']['max'] = $forecast['t']['max'] > 0 ? "+".$forecast['t']['max'] : $forecast['t']['max'];
$forecast['p']['min'] = (string)round($fpart->pressure->attributes()->value,0,PHP_ROUND_HALF_UP);
// $forecast['p']['max'] = (string)$fpart->PRESSURE->attributes()->max;
$forecast['w']['min'] = (string)round($fpart->windSpeed->attributes()->mps,0,PHP_ROUND_HALF_UP);
//$forecast['w']['max'] = (string)$fpart->WIND->attributes()->max;
//$forecast['w']['rumb'] = (string)$fpart->WIND->attributes()->direction;
$forecast['h']['min'] = (string)$fpart->humidity->attributes()->value;
//$forecast['h']['max'] = (string)$fpart->RELWET->attributes()->max;
$forecast['symb'] = (string)$fpart->symbol->attributes()->name;
$forecast['pict'] = (string)$fpart->symbol->attributes()->var;
$date = date('c',strtotime($hoffset.' hours',strtotime($attr['from'])));
$hour = date('H',strtotime($date));
$forecast['timestamp'] =strtotime($date);
$date = strtotime($date);
$dayofweek = date('w',$date);
$date = $weekdays[$dayofweek]." ".date('d.m',$date);
if ($forecast['timestamp'] > time()){
$days[$date][$hour] = $forecast;
}
}
} else {$days=array();}
}
//return array($cityname,$days);
return [$cityname => $days];
//echo [$cityname => $days];
}
part 2
$outputData = array();
if (count($this->forecast) > 0) {
foreach ($this->forecast as $date => $daypart) {
$outputData[] = $date;
foreach ($daypart as $dp => $data) {
$outputData[] = str_pad($dp, 2, '0', STR_PAD_LEFT);
$outputData[] = $data['symb'];
$outputData[] = $data['t']['min'];
$outputData[] = $data['t']['max'];
if (($data['p']['min']) > 0) {
$outputData[] = "Давление " . round($data['p']['min'] * 0.75006375541921) . "мм. рт. ст.";
}
}
}
} else {
$outputData[] = "В данный момент информация о погоде отсутствует";
}
echo implode(' ', $outputData);

Undefined variable: error in adding field into db

I'm getting error:Undefined variable: error
in my code:
public function add(){
$this->polls_model->rules = Pf::event()->trigger("filter","polls-adding-validation-rule",$this->polls_model->rules);
$template = null;
$template = Pf::event()->trigger("filter","polls-add-template",$template);
if ($this->request->is_post()){
$data = array();
$data["polls_question"] = $this->post->{"polls_question"};
$data["polls_pubdate"] = str_to_mysqldate($this->post->{"polls_pubdate"},$this->polls_model->elements_value["polls_pubdate"],"Y-m-d H:i:s");
$data["polls_unpubdate"] = str_to_mysqldate($this->post->{"polls_unpubdate"},$this->polls_model->elements_value["polls_unpubdate"],"Y-m-d H:i:s");
if (is_array($this->post->{"polls_status"})){
$data["polls_status"] = implode(",",$this->post->{"polls_status"});
}else{
$data["polls_status"] = $this->post->{"polls_status"};
}
$port_answer = isset($this->post->{"answer"}) ? $this->post->{"answer"} : array();
$data = Pf::event()->trigger("filter","polls-post-data",$data);
$data = Pf::event()->trigger("filter","polls-adding-post-data",$data);
$var = array();
$pollq_multiple_yes = intval($this->post->{'pollq_multiple_yes'});
$data['polls_multiple'] = 0;
if ($pollq_multiple_yes == 1) {
if(intval($this->post->{'pollq_multiple'}) > count($port_answer)){
$data['polls_multiple'] = 1;
}else{
$data['polls_multiple'] = intval($this->post->{'pollq_multiple'});
}
} else {
$data['polls_multiple'] = 1;
}
//debug($data);
Pf::database()->query('START TRANSACTION');
$inserted = $this->polls_model->insert($data);
if($inserted === false){
Pf::database()->query('ROLLBACK');
}else{
$new_id = $this->polls_model->insert_id();
$insert_meta = true;
if(count($port_answer) > 0){
$custom = array();
$int = count($port_answer);
for ($i = 0; $i < $int ; $i++) {
if(!empty($port_answer[$i])){
$custom = array(
'pollsa_qid' => $new_id,
'pollsa_answers' => e($port_answer[$i]),
);
}
$insert_meta = $this->answers_model->insert($custom);
}
if($insert_meta === false){
Pf::database()->query('ROLLBACK');
}else{
Pf::database()->query('COMMIT');
}
}
Pf::database()->query('COMMIT');
}
$errors = Pf::validator()->get_readable_errors(false);
foreach ($errors as $key => $value) {
$error[$key][0] = $errors[$key][0];
}
$this->view->errors = $error; // error here!
$var['content'] = $this->view->fetch($template);
if (count($error) > 0){// and here!!!
$var['error'] = 1;
}else{
Pf::event()->trigger("action","polls-add-successfully",$this->polls_model->insert_id(),$data);
$var['error'] = 0;
$var['url'] = admin_url($this->action.'=index&ajax=&id=&token=');
}
echo json_encode($var);
}else{
$this->view->render($template);
}
}
I edited code, added function code.
This is my add function, if I want add poll with answers.
It gives me this error to my log.
I found this tutorial Undefined Variable error in View
I've googled it but didnt find anything special what helps me out.
Initiate the variable as an array.
because if the $error is empty the compiler will see it as an array.
if not it will get an error.
$error = [];
$errors = Pf::validator()->get_readable_errors(false);
foreach ($errors as $key => $value) {
// $error[$key][0] = $errors[$key][0];
// the right way is below
// i actually dont know what you want to do but this is the right way
// but providing [0] will make it some how constant.
$error[$key] = $errors[$key]
}
$this->view->errors = $error; // error showing here!
$var['content'] = $this->view->fetch($template);
if (count($error) > 0){ // and here???
$var['error'] = 1;
}else{
Pf::event()->trigger("action","polls-add-successfully",$this->polls_model->insert_id(),$data);
$var['error'] = 0;
$var['url'] = admin_url($this->action.'=index&ajax=&id=&token=');
}

getting the even index of a string

hey guys im trying to get the even indexes of a string from the db then save them in a variable then echo. but my codes seems doesnt work. please help. here it is
require_once('DBconnect.php');
$school_id = '1';
$section_id = '39';
$select_pk = "SELECT * FROM section
WHERE school_id = '$school_id'
AND section_id = '$section_id'";
$query = mysql_query($select_pk) or die (mysql_error());
while ($row = mysql_fetch_assoc($query)) {
$public_key = $row['public_key'];
}
if ($public_key) {
$leng_public_key = strlen($public_key);
$priv_key_extract = "";
$array_pki = array();
for ($i=0; $i <=$leng_public_key-1 ; $i++) {
array_push($array_pki,$public_key[$i]);
}
foreach ($array_pki as $key => $value) {
if($key % 2 == 0) {
$priv_key_extract += $public_key[$key];
} else {
$priv_key_extract ="haiiizzz";
}
}
}
echo $priv_key_extract;
as you can see im trying to use modulo 2 to see if the index is even.
I have updated your code as below, it will work now :
<?php
$public_key = 'A0L8V1I5N9';
if ($public_key) {
$leng_public_key = strlen($public_key);
$priv_key_extract = "";
$array_pki = array();
for ($i=0; $i <=$leng_public_key-1 ; $i++) {
array_push($array_pki,$public_key[$i]);
}
foreach ($array_pki as $key => $value) {
//Changed condition below $key % 2 ==0 => replaced with $key % 2 == 1
if($key % 2 == 1) {
// Changed concatenation operator , += replaced with .=
$priv_key_extract .= $public_key[$key];
} /*else {
//Commented this as it is getting overwritten
$priv_key_extract ="haiiizzz";
}*/
}
}
echo $priv_key_extract;
?>
Try this function
function extractKey($key) {
if (empty($key) || !is_string($key)) return '';
$pkey = '';
for ($i=0;$i<strlen($key);$i++) {
if ($i % 2 == 0) {
$pkey .= $key[$i];
}
}
return $pkey;
}
echo extractKey('12345678'); # => 1357

Why isn't my sorting algorithm working?

I'm developing a system for a client that creates a csv of packing labels which is sent to a printer. The client has six different items. Customers order products in bulk from my client. Two items (product A and product B) share the same packing line. In order to make packing more efficient my client wants to alternate between packing product A and packing product B first.
For example, if John, Sally, and James all ordered both products, the system needs to write John's orders to the csv starting with product A, Sally's orders starting with product B, and James' orders starting with product A again.
I've pasted my non-working code below, but this is really screwing with my head and I'm having a really tough time with it.
foreach($orders as $order) {
$name = null;
$phone = null;
$account = DAO_ContactPerson::get($order->account_id);
$delivery = false;
if($account->is_agency) {
$name = $order->getAttribute('name');
$phone = $order->getAttribute('phone');
} else {
$name = sprintf("%s %s",
$account->getPrimaryAddress()->first_name,
$account->getPrimaryAddress()->last_name
);
$phone = $account->phone;
}
$name = trim($name);
$phone = trim($phone);
$items = $order->getItems();
if($order->getAttribute('delivery')) {
$type = 'deliveries';
$destination = 'Delivery';
$address = sprintf("%s %s %s",
$order->getAttribute('delivery_address.line1'),
$order->getAttribute('delivery_address.line2'),
$order->getAttribute('delivery_address.postal')
);
} else {
$type = 'pickups';
$agency = DAO_ContactPerson::getAgency($order->getAttribute('pickup'));
$destination = $agency->name;
// Override account id so orders are grouped by agency
$order->account_id = $agency->id;
$address = null;
}
// var_dump($order->id);
// Init account array
if(!isset($rows[$type][$order->account_id]))
$rows[$type][$order->account_id] = array('combined' => array(), 'separate' => array());
foreach($items as $item) {
$packing = 'separated';
if($item->product_id == 3 || $item->product_id == 4)
$packing = 'combined';
if(!isset($rows[$type][$order->account_id][$packing][$item->product_id]))
$rows[$type][$order->account_id][$packing][$item->product_id] = array();
$i = 0;
while($i < $item->quantity) {
$rows[$type][$order->account_id][$packing][$item->product_id][] = array(
'number' => $order->id,
'destination' => $destination,
'size' => $item->product_id,
'name' => $name,
'address' => $address,
'phone' => $phone
);
$i++;
}
}
// if($order->id == 176) {
// var_dump($rows[$type][$order->account_id][$packing]);
// }
}
$this->weight = 1;
$pickups = count($rows['pickups']);
for($i = 0; $i < $pickups; $i++) {
$account =& $rows['pickups'][$i];
$account['output'] = array();
if(isset($account['combined'])) {
$combined_products =& $account['combined'];
if(!empty($combined_products)) {
foreach($combined_products as $prod_id => $combined) {
usort($combined_products[$prod_id], array($this, "_compareBoxes"));
}
// Flip weights once we finish with this account
$last_box = end($combined_products);
$last_box = array_pop($last_box);
reset($combined_products);
if($this->weight == 1) {
$this->weight = -1;
if($last_box['size'] == 3) {
asort($combined_products);
}
} else {
if($last_box['size'] == 4) {
arsort($combined_products);
}
$this->weight = 1;
}
foreach($combined_products as $combined) {
$account['output'][] = $combined;
}
foreach($account['separated'] as $separate) {
$account['output'][] = $separate;
}
}
} else {
if(isset($account['separated']))
$account['output'] = $account['separated'];
}
}
$deliveries = count($rows['deliveries']);
for($i = 0; $i < $deliveries; $i++) {
$account =& $rows['deliveries'][$i];
$account['output'] = array();
if(isset($account['combined'])) {
$combined_products =& $account['combined'];
if(!empty($combined_products)) {
foreach($combined_products as $prod_id => $combined) {
usort($combined_products[$prod_id], array($this, "_compareBoxes"));
}
// Flip weights once we finish with this account
$last_box = end($combined_products);
$last_box = array_pop($last_box);
reset($combined_products);
if($this->weight == 1) {
$this->weight = -1;
if($last_box['size'] == 3) {
asort($combined_products);
}
} else {
if($last_box['size'] == 4) {
arsort($combined_products);
}
$this->weight = 1;
}
foreach($combined_products as $combined) {
$account['output'][] = $combined;
}
foreach($account['separated'] as $separate) {
$account['output'][] = $separate;
}
}
} else {
if(isset($account['separated']))
$account['output'] = $account['separated'];
}
}
$rows['output'] = $rows['pickups'];
array_push($rows['output'], $rows['deliveries']);
$output = '';
foreach($rows['output'] as $account_id => $boxes) {
if(!empty($boxes['output'])) {
foreach($boxes['output'] as $labels) {
if(!empty($labels)) {
foreach($labels as $label) {
$output .= implode(',', $label) . "<br>";
}
}
}
}
}
The _compareBoxes method looks like this:
private function _compareBoxes($a, $b) {
if($a['size'] == $b['size']) {
return 0;
}
if($this->weight == 1) {
// Medium first, then Large
return ($a['size'] < $b['size']) ? -1 : 1;
}
if($this->weight == -1) {
// Large first, then Medium
return ($a['size'] > $b['size']) ? -1 : 1;
}
}

Categories