ACF make top 10 based on field value - php

I'm using ACF for a while now and I thought this would be easier but cant figure out how to do this properly...
I'm trying to create some kind of trophy cabinet. So every company has a score that is stored inside a ACF called "company_score".
For example we have companies called Microsoft, Facebook and Twitter. They all have a score:
Facebook = 200000
Microsoft = 900000
Twitter = 100000
So the top 3 wil be like
1) Microsoft
2) Facebook
3) Twitter
I know how to display the value of an ACF but how can I compare all the scores that are stored and when a company has the best score it will display a gold medal. When a company has the second best score it will display a silver medal and so on.
I all had it figured it out in my head but a bit stuck here how to do this.

There could be several approaches to handle this. The first one, which comes in my mind is very simple.
Try these steps:
Pull all fields
Store in an array
Sort the array in ascending order
Display the results.
I hope, you've some understanding of the code but here are the coded guidelines...
<?php
$fields = get_fields();
$company_details = array();
if( $fields ):
foreach( $fields as $name => $value ):
$company_details[ $name ] = $value;
endforeach;
endif;
//to sort by company score
arsort( $company_details );
//loop through the array and display results, like
foreach( $company_details as $name => $value):
echo "Company name is: " .$name. ". Company Score: " . $value;
endforeach;
PS: The code is not tested because the purpose was to share logic with you. So, ignore if there's any error.

Related

Forminator API - Get total value of submission data

I'm attempting at pulling data from my Forminator submissions, but with no joy.Here's what I've got so far;
<?php
$form_id = 43;
$elem_id = 'currency-1';
$fields = Forminator_API::get_form_field( $form_id, $elem_id, $to_array );
var_dump(get_object_vars( $fields ));
currency-1, accepts a value from your input 100, 200 etc. What i'm trying to do is, add all those value together and show frontend.
Any advice is greatly appreachiate, i've spent around 4 hours looking at the api and not worked it out.
It looks like you are looking at the wrong object, in order to pull those number you need to look at the submissions data which is
The below should give you a list of all the entries, you can loop through those and add the numbers together.
<?php
$form_id = 43;
$entries = Forminator_API::get_entries( $form_id );
foreach($entries as $key => $value){
//add all values of currency-1 together
}
?>

How to insert multiple select option in PHP MySQL when multiple='multiple' is enabled

I have a FORM with method POST. In the form I have two select drop-down with multiple='multiple' enabled in both so that user can make multiple selections.
Now I am using MySQL database to store data.
I am using foreach loop to iterate all the selections made.
Here is the image Select drop-down image
My code
$cid = $row['cid'];
$work_location = $_POST['work_location'];
$interest = $_POST['interest'];
foreach ($work_location as $value) {
$work = $value;
}
foreach ($interest as $value) {
$int = $value;
}
$insert_oth_data = "INSERT INTO resume_spec_data
(cid, work_location, interest)
VALUES('$cid', '$work', '$int')";
mysqli_query($con, $insert_oth_data);
echo var_export($work_location);
echo var_export($interest);
echo var_export($work);
echo var_export($int);
echo var_export( $insert_oth_data );
Here work_location and interest are the fields that will carry the multiple select values. I don't want to use implode function because it will make data extraction difficult as table grows. I want to store the values in saperate rows of database.
The problem I am facing is that data is being inserted, but the problem is when I select multiple options only one data is being inserted not all.
The result I get after inserting the data is:
array ( 0 => 'Delhi', 1 => 'NCR', )array ( 0 => 'Software development', 1 => 'Business analyst', 2 => 'Web development', )'NCR''Web development''INSERT INTO resume_spec_data(cid, work_location, interest) VALUES(\'1\', \'NCR\', \'Web development\')'
As you can compare from the image I have made multiple selections. But single data is being taken here
For reference
$work_location contains array ( 0 => 'Delhi', 1 => 'NCR', )
$interest contains
array ( 0 => 'Software development',
1 => 'Business analyst',
2 => 'Web development',
)
$work contains NCR
$int contains Web development only
$work and $int should also contains same as $work_location and $interest respectively.
One thing that I found here is that I have applied Insert query outside the foreach loop maybe that is why only one value is being taken. Since I am using multiple select drop-down here with multiple='multiple' enabled, I don't know how to do this to achieve the result I want.
Any help would be appreciated.
Your INSERT command happens once, and it occurs after your loops have all finished. So in the loops you're pointlessly re-assigning new values to the same variable, and then discarding them again without using them. Obviously if you wait until after a loop has finished, then you can't use the values which are present when the loop is running. You'll only ever see the last one which was assigned in the last run of the loop.
And you've explained that you're struggling to fix this because you don't know how to include the insert query inside the loops, because there are 2 different foreach loops.
So really I think the root cause here is that your database structure is flawed. It seems you permit different numbers of values in your form (e.g. 2 entries for work locations, then 3 entries for domains of interest, per your screenshot), and there's no particular relationship between them (e.g. does "Delhi" belong with "software development, or "business analyst", or the other one? There's no logic to explain that).
And yet, you're trying to store them in a table which inherently relates them together by storing them next to each other in rows. This will result in poor data quality because a) there's no way to decide which belongs with which, and b) if you have different numbers of entries in each field then you'll end up with gaps.
You need separate tables to store each list - one table for locations, and one table for interests, both with the Cid to link them to the master record.
This will then make it easy to use the data in you loops e.g.
foreach ($work_location as $value) {
$work = $value;
//...write query code to insert into work locations table
}
foreach ($interest as $value) {
$int = $value;
//...write query code to insert into interests table
}

Get results from array by not using the key

I have the following code to get an array of looped posts that the user has a status of 'active'.
In that array I have multiple entries for "slug" like this.
["slug"]=>string(9) "the_bbc""
I can't pull in the data based on string number - "string(9)" as they're all different.
How can I echo "the_bbc" by searching for ["slug"] and return all results.
<?php $user_id = get_current_user_id();
$active_memberships = wc_memberships_get_user_memberships( $user_id, 'active' ); // userID and active user ?>
<pre><?php var_dump ($active_memberships, $product_id); ?></pre>
Yes this looks quite novice and have been told yesterday by another person but I'm in my first year in college studying php.
Thanks
If you have multiple "slug" in an array you can loop through it with a foreach(), ex:
foreach ( $active_memberships['slug'] as $slug) {
//do whatever with this variable
}
I hope that I understood you correctly. Please provide a better description next time.

How to delete item ID from array used as session shopping cart

I have a SESSION['cart'] with ID numbers only. I have a form passing the ID with a remove button. Once passed to my controller, I cannot figure out how to write the code that uses the ID ($_POST['id']) to delete the item from the SESSION['cart'].
I can loop through and display the array contents, but I cannot figure out how to delete based on ID passed from the form.
How do I loop through the SESSION['cart'] array to find a match with the ID passed from my delete form, and then delete that ID? I know that unset($_SESSION['cart'][X] deletes the ID at index X, but I cannot figure out how to loop through all the elements to find a match.
I have read a number of related issues in this forum but have been unable to apply any of those solutions to resolve this challenge. Any assistance is appreciated.
The way you have your values ($products = array(3,7,99,152)) isn't a very good method. Every time you want to perform an action, you have to loop through the array, you don't want that. Apart from that, how do you store quantity? Or variations like e.g. size or color?
if your structure is $array[ ID_OF_PRODUCT ], you can simply do this:
unset( $_SESSION['cart'][$_POST['id']] ); // Instant access via the key!
This should be the method to use. This allows you to create an array like this, with advanced info, but with easy access (42/63 are example id's)
$_SESSION['cart']['products'][42] = array(
'quantity' = 11,
'size' = 'large',
'color' = 'blue'
);
$_SESSION['cart']['products'][63] = array(
'quantity' = 9,
'size' = 'small',
'color' = 'red'
);
This way you can access a lot of info with the product ID, and now also see which size and color (both just examples) the user selected. You may not have need for this now, but you will further down the road :)
As you might see, you can easily do stuff with the item:
isset($_SESSION['cart'][$_POST['id']]); // check if the product exists
unset($_SESSION['cart'][$_POST['id']]); // remove the product
echo $_SESSION['cart'][$_POST['id']]['quantity']; // get the quantity.
Not a loop in the code. You should only use loops when you have to, try to somewhat avoid them because often their slow. Say you have an extreme case of 1000 items in your shop, and you need to delete no999... That'll take a noticable moment.
Here is the code to do it right:
$id = $_POST['id'];
$items = $_SESSION["cart"];
if(($key = array_search($id, $items)) !== false) {
unset($items[$key]);
}
$_SESSION["cart"] = array_values($items);
Advice
Beside item ID, you can also sve item count in SESSION array because user can add several times same item into cart. In that case your $_SESSION["card"] should be structured like:
array(
'1'=>12,//Item with ID=1 is added 12 times in shopping cart
'17'=>2,//Item with ID=17 is added 2 times in shopping cart etc.
'32'=>12,
)

How to Implement A Recommendation System?

I've Collective Intelligence book, but I'm not sure how it can be apply in practical.
Let say I have a PHP website with mySQL database. User can insert articles with title and content in the database. For the sake of simplicity, we just compare the title.
How to Make Coffee?
15 Things About Coffee.
The Big Question.
How to Sharpen A Pencil?
Guy Getting Hit in Balls
We open 'How to Make Coffee?' article and because there are similarity in words with the second and fourth title, they will be displayed in Related Article section.
How can I implement this using PHP and mySQL? It's ok if I have to use Python. Thanks in advance.
Store a set of keywords alongside each product, which should essentially be everything in the title besides a set of stop words. When a title is displayed, you find any other products which share keywords in common (with those with one or more in common given priority).
You could further enhance this by assigning a score to each keyword based on its scarcity (with more scarce words being given a higher score, as a match on 'PHP', for instance, is going to be more relevant than a match on 'programming'), or by tracking the number of times a user navigates manually between a set of products.
Regardless you'd best start off by making it simple, and then enhance it as you go on. Depending on the size of your database more advanced techniques may not be all that fruitful.
You're best off using a set of tags which are parsed and stored in the db when the title is inserted, and then querying based on that.
If you have to parse the title though, you'd basically be doing a LIKE query:
SELECT * FROM ENTRIES WHERE TITLE LIKE '%<keyword>%';
For a more verbose answer though:
// You need some test to see if the word is valid.
// "is" should not be considered a valid match.
// This is a simple one based on length, a
// "blacklist" would be better, but that's up to you.
function isValidEntry( $word )
{
return strlen( $word ) >= 4;
}
//to hold all relevant search strings:
$terms = array();
$postTitleWords = explode( ' ' , strtolower( 'How to Make Coffee' ) );
for( $postTitleWords as $index => $word )
{
if( isValidEntry( $word ) ) $terms[] = $word;
else
{
$bef = #$postTitleWords[ $index - 1 ];
if( $bef && !isValidEntry( $bef ) ) $terms[] = "$bef $word";
$aft = #$postTitleWords[ $index + 1 ];
if( $aft && !isValidEntry( $aft ) ) $terms[] = "$word $aft";
}
}
$terms = array_unique( $terms );
if( !count( $terms ) )
{
//This is a completely unique title!
}
$search = 'SELECT * FROM ENTRIES WHERE lower( TITLE ) LIKE \'%' . implode( '%\' OR lower( TITLE ) LIKE \'%' $terms ) . '\'%';
// either pump that through your mysql_search or PDO.
This can be simply achieved by using wildcards in SQL queries. If you have larger texts and the wildcard seems to be unable to capture the middle part of text then check if the substring of one matches the other. I hope this helps.
BTW, your question title asks about implementing recommendation system and the question description just asks about matching a field among database records. Recommendation system is a broad topic and comes with many interesting algorithms (e.g, Collaborative filtering, content-based method, matrix factorization, neural networks, etc.). Please feel free to explore these advanced topics if your project is to that scale.

Categories