How do I search for 2 values in the same record using in_array()?
For example I want to search for 'AuthorNiceName' value and 'AuthorType' value.
The below code does not work how I would like. It should return "EU TEST" but it returns "CP TEST".
Thanks in advance.
$authors = array(
array(
'AuthorName' => 'John Smith',
'AuthorNiceName' => 'john-smith',
'AuthorType' => 'CP'
),
array(
'AuthorName' => 'Joe Bloggs',
'AuthorNiceName' => 'joe-bloggs',
'AuthorType' => 'EU'
),
);
if (in_array('joe-bloggs', array_column($authors, 'AuthorNiceName')) && in_array('EU', array_column($authors, 'AuthorType'))) {
$authorType = 'CP TEST';
}
else {
$authorType = 'EU TEST';
}
echo $authorType;
UPDATE: My latest code using #Philipp's suggestion which I adjusted slightly. However it doesn't work, if there are other users with the same 'AuthorType' it returns "no match"?
$authors = array( //TODO
array(
'AuthorName' => 'John Smith',
'AuthorNiceName' => 'john-smith',
'AuthorType' => 'CP'
),
array(
'AuthorName' => 'Joe Bloggs',
'AuthorNiceName' => 'joe-bloggs',
'AuthorType' => 'EU'
),
array(
'AuthorName' => 'Matt Bat',
'AuthorNiceName' => 'matt-bat',
'AuthorType' => 'EU'
),
);
$name = 'joe-bloggs';
$type = 'EU';
foreach ($authors as $author) {
if ($author['AuthorNiceName'] == $name && $author['AuthorType'] == 'EU') {
$authorType = 'EU Test';
}
elseif ($author['AuthorNiceName'] == $name && $author['AuthorType'] == 'CP') {
$authorType = 'CP Test';
}
else {
$authorType = 'no match';
}
}
echo $authorType; //returns "not match". it should return "EU Test".
It seems, you should use a loop for what you want
$name = 'joe-bloggs';
$type = 'EU';
foreach ($authors as $author) {
if ($author['AuthorNiceName'] == $name && $author['AuthorType'] == $type) {
// do something
}
}
using in_array with array_column looses the information if the result is from the same column. Using array_search, you could also compare the index of the columns, but this seems like a bad solution...
Update
The problem with your update is, you overwrite the $authorType var, after you set the correct value. You should check, if an value is already set and only then set a new value.
$name = 'joe-bloggs';
$authorType = false;
foreach ($authors as $author) {
if ($author['AuthorNiceName'] == $name && $author['AuthorType'] == 'EU') {
$authorType = 'EU Test';
} elseif ($author['AuthorNiceName'] == $name && $author['AuthorType'] == 'CP') {
$authorType = 'CP Test';
}
}
if ($authorType === false) {
echo 'no match';
} else {
echo $authorType;
}
Related
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.
I want to display Yes if one of the type values begins with the letter p, however I keep outputting NONO. Any help greatly appreciated...`
<?php
$pals[] = array('name' => 'jon' , 'type' => 'peach');
$pals[] = array('name' => 'gore' , 'type' => 'choc');
foreach($pals as $key => $value) {
if (substr($value['type'], 0) === "p") {
echo "Yes";
} else {
echo "NO";
}
}
Update this line :
if (substr($value['type'], 0,1) === "p") {
Try substr($value['type'],0, 1)
To make it without substr, if you want
<?php
$pals[] = array('name' => 'jon' , 'type' => 'peach');
$pals[] = array('name' => 'gore' , 'type' => 'choc');
foreach($pals as $key => $value) {
$type = trim($value["type"]);
if ($type[0] === "p") {
echo "$type : Yes\n";
} else {
echo "$type : NO";
}
}
?>
live demo : https://eval.in/754179
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
<?php
static $cnt=0;
$name='victor';
$coll = array(
'dep1'=>array(
'fy'=>array('john','johnny','victor'),
'sy'=>array('david','arthur'),
'ty'=>array('sam','joe','victor')
),
'dep2'=>array(
'fy'=>array('natalie','linda','molly'),
'sy'=>array('katie','helen','sam','ravi','vipul'),
'ty'=>array('sharon','julia','maddy')
)
);
function array_find($name,$arr)
{
global $cnt;
if(!(is_array($arr)))
return false;
foreach($arr as $val)
{
if(is_array($val))
array_find($name,$val);
else
{
$val=strtolower($val);
$item=strtolower($name);
if($val==$name)
$cnt+=1;
}
}
}
array_find($name,$coll);
if($cnt==0)
echo "$name was Not Found";
else
echo "$name was found $cnt times.";
Try this code, hope it will work
<?php
static $cnt = 0;
$name = 'victor';
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
function recursive_search(&$v, $k, $search_query){
global $cnt;
if($v == $search_query){
++$cnt;
}
}
array_walk_recursive($coll, 'recursive_search' , $name);
if ($cnt == 0)
echo "$name was Not Found";
else
echo "$name was found $cnt times.";
DEMO
I searched in Google and consulted the PHP documentation, but couldn't figure out how the following code works:
$some='name=Licensing Module;nextduedate=2013-04-10;status=Active|name=Test Addon;nextduedate=2013-04-11;status=Active';
function getActiveAddons($somet) {
$addons = array( );
foreach ($somet as $addon) {
if ($addon['status'] == 'Active') {
$addons[] = $addon['name'];
continue;
}
}
return $addons;
}
echo (count( getActiveAddons( $some ) ) ? implode( '<br />', getActiveAddons( $some ) ) : 'None');
The code always echo's None.
Please help me in this.
I don't know where you got this code from but you've initialized $some the wrong way. It is expected as an array like this:
$some = array(
array(
'name' => 'Licensing Module',
'nextduedate' => '2013-04-10',
'status' => 'Active'
),
array(
'name' => 'Test Addon'
'nextduedate' => '2013-04-11',
'status' => 'Active'
)
);
I guess the article you've read is expecting you to parse the original string into this format.
You can achieve this like this:
$string = 'name=Licensing Module;nextduedate=2013-04-10;status=Active|name=Test Addon;nextduedate=2013-04-11;status=Active';
$result = array();
foreach(explode('|', $string) as $record) {
$item = array();
foreach(explode(';', $record) as $column) {
$keyval = explode('=', $column);
$item[$keyval[0]] = $keyval[1];
}
$result[]= $item;
}
// now call your function
getActiveAddons($result);
$some is not an array so foreach will not operate on it. You need to do something like
$some = array(
array(
'name' => 'Licensing Module',
'nextduedate' => '2013-04-10',
'status' => 'Active'
),
array(
'name' => 'Test Addon',
'nextduedate' => '2013-04-11',
'status'=> 'Active'
)
);
This will create a multidimensional array that you can loop through.
function getActiveAddons($somet) {
$addons = array( );
foreach ($somet as $addon) {
foreach($addon as $key => $value) {
if ($key == 'status' && $value == 'Active') {
$addons[] = $addon['name'];
continue;
}
}
}
return $addons;
}
First, your $some variable is just a string. You could parse the string into an array using explode(), but it's easier to just start as an array:
$some = array(
array(
"name" => "Licensing Module",
"nextduedate" => "2013-04-10",
"status" => "Active",
),
array(
"name" => "Test Addon",
"nextduedate" => "2013-04-11",
"status" => "Active",
)
);
Now, for your function, you are on the right track, but I'll just clean it up:
function getActiveAddons($somet) {
if (!is_array($somet)) {
return false;
}
$addons = array();
foreach ($somet as $addon) {
if ($addon['status'] == 'Active') {
$addons[] = $addon['name'];
}
}
if (count($addons) > 0) {
return $addons;
}
return false;
}
And finally your output (you were calling the function twice):
$result = getActiveAddons($some);
if ($result === false) {
echo "No active addons!";
}
else {
echo implode("<br />", $result);
}