Checking if key exists in array [duplicate] - php

This question already has answers here:
Giving my function access to outside variable
(6 answers)
Closed 6 years ago.
EDIT:
if(array_key_exists($errcode, $Errors)){
$Data['status'] = -1;
$Data['err'] = array(
"err_code" => $errcode,
"err_str" => $Errors[$errcode]
);
}
I'm having a harsh time figuring out if a key exists in an array, I've tried using array_key_exists method, but no luck! I've also tried empty($array[$key]) which seems to return the same generic error rather than the specific one.
Calling err(null, 3) will output:
{
"status": -1,
"err": {
"err_code": null,
"err_str": "Generic error"
}
}
I've tried using the array_key_exists method which returns a bool but it doesn't seem to work, why is this?
My site should output error 5: Invalid
//Errors ENUM
$Errors = array(
0 => "Cannot parse <GameID>",
1 => "Invalid steam session",
2 => "Invalid <GameID>, non-numeric",
3 => "SQL Connection refused",
4 => "SQL Query error",
5 => "invalid <GameID>"
);
function err($status, $errcode){
if(isset($errcode)){
if($Errors[$errcode] != null){
$Data['status'] = -1;
$Data['err'] = array(
"err_code" => $errcode,
"err_str" => $Errors[$errcode]
);
} else {
$Data['status'] = -1;
$Data['err'] = array(
"err_code" => null,
"err_str" => "Generic error"
);
}
} else {
$Data['status'] = $status;
$Data['err'] = array(
"err_code" => null,
"err_str" => null
);
}
echo(json_encode($Data, 128 | 32));
}

The err function doesn't see global $Errors variable. Declare Errors variable as global inside Err function:
function err($status, $errcode){
global $Errors;
if(isset($errcode)){
if($Errors[$errcode] != null){
$Data['status'] = -1;
$Data['err'] = array(
"err_code" => $errcode,
"err_str" => $Errors[$errcode]
);
} else {
$Data['status'] = -1;
$Data['err'] = array(
"err_code" => null,
"err_str" => "Generic error"
);
}
} else {
$Data['status'] = $status;
$Data['err'] = array(
"err_code" => null,
"err_str" => null
);
}
echo(json_encode($Data, 128 | 32));
}

Related

Creating default object from empty value through an array

I have read multiple threads here about the matter, although none of the solutions seem to be similar to mine. I would have attempted to fix this myself but unable to find anything similar I don't even know where to begin. Why am I getting this error, and what are the proper steps to resolve it?
function handleRequestsave_details()
{
$this->vbulletin->input->clean_array_gpc('p', array('fullname' => TYPE_STR,
'address_1' => TYPE_STR, 'address_2' => TYPE_STR, 'address_city' => TYPE_STR,
'address_state' => TYPE_STR, 'address_zip' => TYPE_STR, 'country' => TYPE_STR,
'phone' => TYPE_STR, 'company' => TYPE_STR));
if ($this->checkDetailsFields('details', $this->vbphrase['memarea_required_fields']))
{
$information = $this->buildInfoArray();
$this->vbulletin->userinfo['ma_info'] = $information;
$this->vbulletin->userinfo['usergroupid'] = $usergrpid;
if ($this->setCustomerNumber($information, $usergrpid))
{
$vbulletin->url = 'members.php?' . $vbulletin->session->vars['sessionurl'] . "do=details";
eval(print_standard_redirect('memarea_saved_details', true, true));
}
}
}
Here are the other functions included in this script, This is not my code it is simply an old product for vBulletin 3.x I am trying to update for my site. this portion throwing the error is when customers enter their billing details to save in their profile.
function checkDetailsFields($requested, $errormessage)
{
if (empty($this->vbulletin->GPC['fullname']) or empty($this->vbulletin->GPC['address_1']) or
empty($this->vbulletin->GPC['address_city']) or empty($this->vbulletin->GPC['address_zip']) or
empty($this->vbulletin->GPC['country']) or empty($this->vbulletin->GPC['phone']))
{
//$GLOBALS['error'] = $errormessage;
eval(standard_error($errormessage));
//$this->handleRequest($requested);
return false;
}
return true;
}
function buildInfoArray()
{
return array('fullname' => $this->vbulletin->GPC['fullname'], 'address_1' => $this->
vbulletin->GPC['address_1'], 'address_2' => $this->vbulletin->GPC['address_2'],
'address_city' => $this->vbulletin->GPC['address_city'], 'address_state' => $this->
vbulletin->GPC['address_state'], 'address_zip' => $this->vbulletin->GPC['address_zip'],
'country' => $this->vbulletin->GPC['country'], 'phone' => $this->vbulletin->GPC['phone'],
'company' => $this->vbulletin->GPC['company']);
}
function setCustomerNumber($ma_info, $usergroup = '', $usevb = true, $userinfo = '')
{
if ($usevb == false)
{
$this->vbulletin->userinfo = &$userinfo;
}
$fcust = $this->fields['custnum'];
$fpass = $this->fields['mpassword'];
$finfo = $this->fields['info'];
$userdm = datamanager_init('User', $this->vbulletin, ERRTYPE_ARRAY);
$userinfo = fetch_userinfo($this->vbulletin->userinfo['userid']);
$userdm->set_existing($userinfo);
if (!$this->vbulletin->userinfo["$fcust"] and !$this->vbulletin->userinfo["$fpass"])
{
$rand = rand($this->vbulletin->options['memarea_numstart'], $this->vbulletin->
options['memarea_numend']);
$num = $this->vbulletin->options['custnum_prefix'] . substr(md5($rand), 0, $this->
vbulletin->options['memarea_custnumleng'] - strlen($this->vbulletin->options['custnum_prefix']));
$userdm->set($fcust, $num);
$pass = substr(md5(time() . $num . $rand . rand(0, 2000)), 0, $this->vbulletin->
options['memarea_custnumleng']);
$userdm->set($fpass, $pass);
$this->sendCustomerInfo($this->vbulletin->userinfo['userid'], $this->vbulletin->
userinfo['username'], $this->vbulletin->userinfo['email'], $num, $pass);
}
if ($usergroup or $usergroup !== '' or $usergroup !== '0')
{
if ($usergroup != $this->vbulletin->userinfo['usergroupid'])
{
$ma_info['oldgroup'] = $this->vbulletin->userinfo['usergroupid'];
$userdm->set('usergroupid', $usergroup);
}
}
if ($ma_info)
{
$ma_info = serialize($ma_info);
$userdm->set($finfo, $ma_info);
}
$userdm->pre_save();
if (count($userdm->errors) == 0)
{
$userdm->save();
return true;
}
else
{
var_dump($userdm->errors);
return false;
}
}

Parsing returns an empty value

I make a parser of items from DotA 2 user inventory in the Steam service. Every time I try to parse user data, I get an empty value:
{"success":true,"items":[]}, but there are items in my Steam inventory.
My function to parse items:
public function loadMyInventory() {
if(Auth::guest()) return ['success' => false];
$prices = json_decode(Storage::get('prices.txt'), true);
$response = json_decode(file_get_contents('https://steamcommunity.com/inventory/'.$this->user->steamid64.'/570/2?l=russian&count=5000'), true);
if(time() < (Session::get('InvUPD') + 5)) {
return [
'success' => false,
'msg' => 'Error, repeat in '.(Session::get('InvUPD') - time() + 5).' сек.',
'status' => 'error'
];
}
//return $response;
$inventory = [];
foreach($response['assets'] as $item) {
$find = 0;
foreach($response['descriptions'] as $descriptions) {
if($find == 0) {
if(($descriptions['classid'] == $item['classid']) && ($descriptions['instanceid'] == $item['instanceid'])) {
$find++;
# If we find the price of an item, then move on.
if(isset($prices[$descriptions['market_hash_name']])) {
# Search data
$price = $prices[$descriptions['market_hash_name']]*$this->config->curs;
$class = false;
$text = false;
if($price <= $this->config->min_dep_sum) {
$price = 0;
$text = 'Cheap';
$class = 'minPrice';
}
if(($descriptions['tradable'] == 0) || ($descriptions['marketable'] == 0)) {
$price = 0;
$class = 'minPrice';
$text = 'Not tradable';
}
# Adding to Array
$inventory[] = [
'name' => $descriptions['market_name'],
'price' => floor($price),
'color' => $this->getRarity($descriptions['tags']),
'tradable' => $descriptions['tradable'],
'class' => $class,
'text' => $text,
'classid' => $item['classid'],
'assetid' => $item['assetid'],
'instanceid' => $item['instanceid']
];
}
}
}
}
}
Session::put('InvUPD', (time() + 5));
return [
'success' => true,
'items' => $inventory
];
}
But should return approximately the following value:
{"success":true,"items":[{"classid":"2274725521","instanceid":"57949762","assetid":"18235196074","market_hash_name":"Full-Bore Bonanza","price":26}]}
Where my mistake?
First of all, you are iterating on descriptions for every assets, which is assets*descriptions iteration, it's quite a lot, but you can optimize this.
let's loop once for descriptions and assign classid and instanceid as object key.
$assets = $response["assets"];
$descriptions = $response["descriptions"];
$newDescriptions=[];
foreach($descriptions as $d){
$newDescriptions[$d["classid"]][$d["instanceid"]] = $d;
}
this will give as the ability to not loop over description each time, we can access the description of certain asset directly $newDescriptions[$classid][$instanceid]]
foreach($assets as $a){
if(isset($newDescriptions[$a["classid"]]) && isset($newDescriptions[$a["classid"]][$a["instanceid"]])){
$assetDescription = $newDescriptions[$a["classid"]][$a["instanceid"]];
$inventory = [];
if(isset($prices[$assetDescription["market_hash_name"]])){
$price = $prices[$assetDescription['market_hash_name']]["price"]*$this->config->curs;
$class = false;
$text = false;
if($price <= $this->config->min_dep_sum) {
$price = 0;
$text = 'Cheap';
$class = 'minPrice';
}
if(($assetDescription['tradable'] == 0) || ($assetDescription['marketable'] == 0)) {
$price = 0;
$class = 'minPrice';
$text = 'Not tradable';
}
$inventory["priceFound"][] = [
'name' => $assetDescription['market_name'],
'price' => floor($price),
'color' => $this->getRarity($assetDescription['tags']),
'tradable' => $assetDescription['tradable'],
'class' => $class,
'text' => $text,
'classid' => $a['classid'],
'assetid' => $a['assetid'],
'instanceid' => $a['instanceid']
];
}else{
$inventory["priceNotFound"][] = $assetDescription["market_hash_name"];
}
}
}
About your mistake:
are you Sure your "prices.txt" contains market_hash_name?
I don't see any other issue yet, operationg on the data you have provided in comment, I got print of variable $assetDescription. Please doublecheck variable $prices.

ErrorException (E_NOTICE) Trying to get property 'sentimen' of non-object [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 3 years ago.
Help, I get an error message ErrorException (E_NOTICE) Trying to get property 'sentimen' of non-object
public function prediksi()
{
$collection = array();
$title = "Data Prediksi Sentimen";
$testing_data = DataTesting::count();
$klasifikasi = DataTesting::with(['data_crawling','klasifikasi'])->get();
foreach($klasifikasi as $class){
$prediksi = Klasifikasi::with(['sentimen'])->where('id_testing',$class->id_testing)->first();
$hasil = Hasil::where('id_testing',$class->id_testing)->get();
$aktual = Sentimen::where('id_sentimen', $class->data_crawling->id_sentimen)->first();
$collection[] = [
'id_testing' => $class->id_testing,
'username' => $class->data_crawling->username,
'tweet' => $class->data_crawling->tweet,
'kategori' => $aktual->kategori,
'prediksi' => $prediksi->sentimen->kategori,
];
}
return view('visualisasi.prediksi', compact(['title','collection','testing_data','hasil']));
}
View Code
Think if your queries and relationship is correct then use like below with IF() conditions
public function prediksi()
{
$collection = array();
$title = "Data Prediksi Sentimen";
$testing_data = DataTesting::count();
$klasifikasi = DataTesting::with(['data_crawling','klasifikasi'])->get();
foreach($klasifikasi as $class){
$prediksi = Klasifikasi::with(['sentimen'])->where('id_testing',$class->id_testing)->first();
$hasil = Hasil::where('id_testing',$class->id_testing)->get();
$aktual = Sentimen::where('id_sentimen', $class->data_crawling->id_sentimen)->first();
if($prediksi && isset($prediksi->sentimen)){
$collection[] = [
'id_testing' => $class->id_testing,
'username' => $class->data_crawling->username,
'tweet' => $class->data_crawling->tweet,
'kategori' => $aktual->kategori,
'prediksi' => $prediksi->sentimen->kategori,
];
}
}
return view('visualisasi.prediksi', compact(['title','collection','testing_data','hasil']));
}
UPDATED
public function prediksi()
{
$collection = array();
$title = "Data Prediksi Sentimen";
$testing_data = DataTesting::count();
$klasifikasi = DataTesting::with(['data_crawling','klasifikasi'])->get();
foreach($klasifikasi as $class){
$prediksi = Klasifikasi::with(['sentimen'])->where('id_testing',$class->id_testing)->first();
$hasil = Hasil::where('id_testing',$class->id_testing)->get();
$aktual = Sentimen::where('id_sentimen', $class->data_crawling->id_sentimen)->first();
if($prediksi && isset($prediksi->sentimen)){
$collection[] = [
'id_testing' => $class->id_testing,
'username' => $class->data_crawling->username,
'tweet' => $class->data_crawling->tweet,
'kategori' => $aktual->kategori,
'prediksi' => $prediksi->sentimen->kategori,
];
$hasil_data[$class->id_testing][] = $hasil;
}
}
return view('visualisasi.prediksi', compact(['title','collection','testing_data','hasil_data']));
}
then in your view when you foreach you collection data
foreach($collection as $key){
//to use hasil data
foreach($hasil_data[$key['id_testing']] as $hasil){
dd($hasil);
}
}

WooCommerce: Check if coupon is valid

I am trying to check if a coupon is still valid (hasn't reached its usage limit) and display content under this condition.
The reason for this is that I want to be able to hand out a coupon code to particular visitors, but obviously don't want to hand out a coupon that has already reached it's usage limit.
I am trying to achieve this with PHP and imagine the code to be something like this:
<?php if (coupon('mycouponcode') isvalid) {
echo "Coupon Valid"
} else {
echo "Coupon Usage Limit Reached"
} ?>
Any help here would be great :)
I believe the recommended way encouraged by WooCommerce is to use the \WC_Discounts Class. Here is an example:
function is_coupon_valid( $coupon_code ) {
$coupon = new \WC_Coupon( $coupon_code );
$discounts = new \WC_Discounts( WC()->cart );
$response = $discounts->is_coupon_valid( $coupon );
return is_wp_error( $response ) ? false : true;
}
Note: It's also possible to initialize the WC_Discounts class with a WC_Order object as well.
It's important to remember doing that inside the wp_loaded hook at least, like this:
add_action( 'wp_loaded', function(){
is_coupon_valid('my-coupon-code');
});
There is an apparent simpler method is_valid() from the WC_Coupon class but it was deprecated in favor of WC_Discounts->is_coupon_valid()
$coupon = new WC_Coupon( 'my-coupon-code' );
$coupon->is_valid();
$code = 'test123';
$coupon = new WC_Coupon($code);
$coupon_post = get_post($coupon->id);
$coupon_data = array(
'id' => $coupon->id,
'code' => $coupon->code,
'type' => $coupon->type,
'created_at' => $coupon_post->post_date_gmt,
'updated_at' => $coupon_post->post_modified_gmt,
'amount' => wc_format_decimal($coupon->coupon_amount, 2),
'individual_use' => ( 'yes' === $coupon->individual_use ),
'product_ids' => array_map('absint', (array) $coupon->product_ids),
'exclude_product_ids' => array_map('absint', (array) $coupon->exclude_product_ids),
'usage_limit' => (!empty($coupon->usage_limit) ) ? $coupon->usage_limit : null,
'usage_count' => (int) $coupon->usage_count,
'expiry_date' => (!empty($coupon->expiry_date) ) ? date('Y-m-d', $coupon->expiry_date) : null,
'enable_free_shipping' => $coupon->enable_free_shipping(),
'product_category_ids' => array_map('absint', (array) $coupon->product_categories),
'exclude_product_category_ids' => array_map('absint', (array) $coupon->exclude_product_categories),
'exclude_sale_items' => $coupon->exclude_sale_items(),
'minimum_amount' => wc_format_decimal($coupon->minimum_amount, 2),
'maximum_amount' => wc_format_decimal($coupon->maximum_amount, 2),
'customer_emails' => $coupon->customer_email,
'description' => $coupon_post->post_excerpt,
);
$usage_left = $coupon_data['usage_limit'] - $coupon_data['usage_count'];
if ($usage_left > 0) {
echo 'Coupon Valid';
}
else {
echo 'Coupon Usage Limit Reached';
}
The code is tested and fully functional.
Reference
WC_API_Coupons::get_coupon( $id, $fields )
add_action( 'rest_api_init', 'coupon' );
function coupon($request) {
register_rest_route('custom-plugin', '/coupon_code/',
array(
'methods' => 'POST',
'callback' => 'coupon_code',
)
);
}
function coupon_code($request)
{
$code = $request->get_param('coupon');
$applied_coupon = $request->get_param('applied_coupon');
$cart_amount = $request->get_param('cart_amount');
$user_id = $request->get_param('user_id');
// $code = 'test123';
$coupon = new WC_Coupon($code);
$coupon_post = get_post($coupon->id);
$coupon_data = array(
'id' => $coupon->id,
'code' => esc_attr($coupon_post->post_title),
'type' => $coupon->type,
'created_at' => $coupon_post->post_date_gmt,
'updated_at' => $coupon_post->post_modified_gmt,
'amount' => wc_format_decimal($coupon->coupon_amount, 2),
'individual_use' => ( 'yes' === $coupon->individual_use ),
'product_ids' => array_map('absint', (array) $coupon->product_ids),
'exclude_product_ids' => array_map('absint', (array) $coupon->exclude_product_ids),
'usage_limit' => (!empty($coupon->usage_limit) ) ? $coupon->usage_limit : null,
'usage_count' => (int) $coupon->usage_count,
'expiry_date' => (!empty($coupon->expiry_date) ) ? date('Y-m-d', $coupon->expiry_date) : null,
'enable_free_shipping' => $coupon->enable_free_shipping(),
'product_category_ids' => array_map('absint', (array) $coupon->product_categories),
'exclude_product_category_ids' => array_map('absint', (array) $coupon->exclude_product_categories),
'exclude_sale_items' => $coupon->exclude_sale_items(),
'minimum_amount' => wc_format_decimal($coupon->minimum_amount, 2),
'maximum_amount' => wc_format_decimal($coupon->maximum_amount, 2),
'customer_emails' => $coupon->customer_email,
'description' => $coupon_post->post_excerpt,
);
if ($coupon_data['code'] != $code) {
$response['status'] = "failed";
$response['message'] = "COUPON ".$code." DOES NOT EXIST!";
return new WP_REST_Response($response);
}
$Acoupon = new WC_Coupon($applied_coupon);
// print_r($Acoupon);exit();
if($Acoupon->individual_use == 'yes'){
$response['status'] = "failed";
$response['message'] = "SORRY, COUPON ".$applied_coupon." HAS ALREADY BEEN APPLIED AND CANNOT BE USED IN CONJUNCTION WITH OTHER COUPONS.";
$response['result'] = $Acoupon->individual_use;
return new WP_REST_Response($response);
}
if ($coupon_data['minimum_amount'] > $cart_amount) {
$response['status'] = "failed";
$response['message'] = "THE MINIMUM SPEND FOR THIS COUPON IS $".$coupon_data['minimum_amount'].".";
return new WP_REST_Response($response);
}
if ($coupon_data['maximum_amount'] < $cart_amount) {
$response['status'] = "failed";
$response['message'] = "THE MAXIMUM SPEND FOR THIS COUPON IS $".$coupon_data['maximum_amount'].".";
return new WP_REST_Response($response);
}
if ($coupon_data['exclude_sale_items'] == true) {
$response['status'] = "failed";
$response['message'] = "SORRY, THIS COUPON IS NOT VALID FOR SALE ITEMS.";
return new WP_REST_Response($response);
}
$usage_left = $coupon_data['usage_limit'] - $coupon_data['usage_count'];
if ($usage_left == 0) {
$response['status'] = "failed";
$response['message'] = "SORRY, COUPON USAGE LIMIT HAS BEEN REACHED.";
return new WP_REST_Response($response);
}
$current_time = date('Y-m-d');
$coupon_Expiry_date = $coupon->expiry_date;
if ($coupon_Expiry_date < $current_time) {
$response['status'] = "failed";
$response['message'] = "THIS COUPON HAS EXPIRED.";
return new WP_REST_Response($response);
}
$user_limite = get_post_meta($coupon_data['id'], 'usage_limit_per_user', true);
$p_id = $coupon_data['id'];
global $wpdb;
$count_of_per_user = $wpdb->get_results("SELECT * FROM wp_postmeta where post_id = $p_id and meta_key = '_used_by' and meta_value = $user_id");
$count = count($count_of_per_user);
if ( $count >= $user_limite) {
$response['status'] = "failed"`enter code here`;
$response['message'] = "COUPON USAGE LIMIT HAS BEEN REACHED.";
return new WP_REST_Response($response);
}enter code here
else{
$response['status'] = "Success";
$response['message'] = "COUPON APPLIED.";
return new WP_REST_Response($response);
}
}
use this function

Insert data from array_push to database in codeigniter

Hi i hava data in array like this :
$data = Array
(
[0] => Array
(
[kode_pbt] => PBT3-2012-10-19
[kodebr] => 8992802618731
[harga] => 25905.00
[jml] => 1
[subtotal_harga] => 25905
)
[1] => Array
(
[kode_pbt] => PBT3-2012-10-19
[kodebr] => 8992388112401
[harga] => 1340.00
[jml] => 1
[subtotal_harga] => 1340
)
)
my problem is when i want to insert to database
white this code : $this->db->insert($table, $data)
i got an error:
Message: Array to string conversion
I have changed to $this->db->insert_batch($table, $data), but i got error '500 internal server error'.
Thank for your assist.
This is my full function code in controller :
function save_pbt($kode = -1) {
$pbt_detail = array();
$pbt_data = array(
'kode_pbt' => trim($this->input->post('kode_pbt')),
'unit_pemakai' => trim($this->input->post('unit_pemakai')),
'jml_item' => trim($this->input->post('jml_item')),
'total_harga' => trim($this->input->post('total_harga')),
'tgl_pbt' => date('Y-m-d'),
'status' => 0
);
for ($i = 0; $i <= $this->input->post('max_i'); $i++) {
if ($this->input->post('kodebr' . $i)) {
$detail_pbt = array(
'kode_pbt' => $this->input->post('kode_pbt'),
'kodebr' => $this->input->post('kodebr' . $i),
'harga' => $this->input->post('beli' . $i),
'jml' => $this->input->post('jml' . $i),
'subtotal_harga' => $this->input->post('subtotal' . $i)
);
array_push($pbt_detail, $detail_pbt);
}
}
$this->db->trans_begin();
$this->Pbt_model->insert_pbt($pbt_data);
$this->Pbt_model->insert_detail_pbt($pbt_detail);
if ($this->db->trans_status() == FALSE) {
$this->db->trans_rollback();
echo "TRANSACTION ROLLBACK";
} else {
$pbt_data['detail'] = $pbt_detail;
$url = SERVER_SIKOPIT . 'service/service?process=pbt&api_key=' . API_KEY;
$response = json_encode($this->rest_helper($url, $pbt_data, "POST"));
echo $response;
$response = json_decode($response);
if ($response->status == true) {
$this->db->trans_commit();
echo "TRANSACTION SUCCESS";
redirect(site_url('receivings'));
} else {
$this->db->trans_rollback();
echo "INSERT PBT BARU GAGAL !!";
echo "TRANSACTION ROLLBACK";
}
}
}

Categories