Although, I have successfully implemented Google Keyword Planner API to generate Keyword Ideas in PHP with the link below.
https://developers.google.com/google-ads/api/docs/keyword-planning/generate-keyword-ideas
Does anyone know the fastest way to sort the result by AvgMonthlySearches?
// Iterate over the results and print its detail.
foreach ($response->iterateAllElements() as $result) {
/** #var GenerateKeywordIdeaResult $result */
// Note that the competition printed below is enum value.
// For example, a value of 2 will be returned when the competition is 'LOW'.
// A mapping of enum names to values can be found at KeywordPlanCompetitionLevel.php.
printf(
"Keyword idea text '%s' has %d average monthly searches and competition as %d.%s",
$result->getText(),
is_null($result->getKeywordIdeaMetrics()) ?
0 : $result->getKeywordIdeaMetrics()->getAvgMonthlySearches(),
is_null($result->getKeywordIdeaMetrics()) ?
0 : $result->getKeywordIdeaMetrics()->getCompetition(),
PHP_EOL
);
}
Thanks
You could implement a function that can compare two instances of your object and use usort:
function cmp($a, $b) {
return $a->getKeywordIdeaMetrics()->getAvgMonthlySearches() - $b->getKeywordIdeaMetrics()->getAvgMonthlySearches();
}
$list = iterator_to_array($response->->iterateAllElements());
usort($list, "cmp");
// $list will be your sorted array to work with from here onwards ...
See more:
Sort array of objects by object fields
https://www.php.net/manual/en/function.iterator-to-array.php
Related
I am working with codeigniter and i want to fetch recods as "two arrays"
based on condition (FilterType='Tag',FilterType='Merchant')
Here is my table "filterproducts"
id FilterType CategoryUrl
1 Tag abc
2 Tag xyz
3 Merchant abc
4 Merchant abc
Here is my current code which is giving me multidimenional array
function SearctRecords()
{
$this->db->select("*")
->from("filterproducts fp")
->join("filterid fi", "fp.FilterType=fi.name")
->where("fp.CategoryUrl", $CategoryUrl);
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
Here is my controller
function SearchFilterProducts()
{
$users['data'] = $this->Customer_model->SearctRecords($CategoryUrl);
$responseJSON = array("Status" => $status, "data" => $users['data']);
header("content-type:application/json");
$response = json_encode($responseJSON);
echo $response;
}
I would recommend to sort using existing DB sorting methods. Usually will perform better than custom PHP function.
I you still want to sort your multidimensional result, consider using usort.
function custom_super_comparator($a, $b) {
//custom comparison
}
usort($response, "custom_super_comparator");
Check this good answer on this topic:
Sort array of objects by object fields
offtopic, SearctRecords is missing the argument
SearctRecords($CategoryUrl) {
I have an array as follows:
$aq=['jonathan','paul','andy','rachel'];
Then I have an array as follows:
$bq=['rachel','andy','jonathan'];
What I need is to use the ordering of the first array to sort my second array.
So for this instance, the resulting sorted array should be:
$cq=['jonathan','andy','rachel'];
I started working on a solution that uses the highest key as the top value (the head of the array) because what Im looking for is the top value but that ran into issues and seemed more like a hack so i think sorting is what im looking for.
Is there a simple function in php that can sort my data based on my first array and there respective positions in the array
please try this short and clean solution using array_intersect:
$aq = ['jonathan','paul','andy','rachel'];
$bq = ['rachel','andy','jonathan'];
$cq = array_intersect($aq, $bq);
var_export($cq);
the output will be :
array ( 0 => 'jonathan', 2 => 'andy', 3 => 'rachel', )
You'll have to use a custom sort function. Here we grab the keys of corresponding entries in the "ordering" array and use them to order the working array.
In this example, we give up (return 0) if the key doesn't exist in the ordering array; you may wish to customize that behavior, but this should give you the general idea.
$order = ['jonathan','paul','andy','rachel'];
$arrayToSort =['rachel','andy','jonathan'];
usort($arrayToSort,function($a,$b) use ($order){
if( ! array_key_exists($a,$order) ) return 0;
if( ! array_key_exists($b,$order) ) return 0;
if( array_search($a,$order) > array_search($b,$order)
return 1;
return -1;
});
I have this simple foreach call that outputs a list of components and is working fine.
foreach ($config["components"] as $component_index => $component) {
echo '<li>$component['name']</li>';
}
The issue is however that the values in the foreach loop order are pre-defined and can't be changed but I need to output them in a different order.
Is it possible to re-arrange them into a custom order (That doesn't follow any standard direction, alphabetical, numerical, etc.)
Take a look at some of these http://php.net/manual/en/array.sorting.php,
CUSTOM ordering like, having apple, pear, orange, and wanting them in orange, apple, pear order isn't possible without literally adding them in yourself.
You COULD say...
if($component == "thisOne"){
add to array
}elseif($component == "thisOtherOne"{
add to array
}elseif....
From ranking your highest to lowest but that's very inefficient..
As you need a custom sorting algorithm, you can use usort function. From what I can see in the question, you don't care about indices, therefore you can do something like this:
$components = usort(
array_values($config['components']),
function ($a, $b)
{
//provide your custom sort function here
//$a and $b are two "components"
//for any given pair of $a and $b
//return -1 if $a should go before $b,
//return 0 if they are the same
//return 1 if $a should go after $b
}
);
foreach ($components as $component) {
$echo "<li>{$component['name']}</li>";
}
Have a look at usort function documentation for more information.
I have a symfony problem: The functionally works good, but this does not work the way I want.
$res = array("4","2","1","3"); // LIST ID (a.id)
$paginas = new sfDoctrinePager('TbArticle', 2);
$paginas->setQuery(Doctrine::getTable('TbArticle')->createQuery('a')->where('a.ifactive = 1')->andWhere('a.dirimage=1')->andWhere('a.stock<>0')->whereIn("a.id", $res));
$paginas->setPage($page);
$paginas->init();
It works okay, but when I call getResults(), the array order is incorrect. For instance, this sort returns: 1,2,3,4. And I like to get: 4, 2, 1, 3 ($res)
Can you help me?
Unfortubately this cannot be done with the query.
The MySQL queries can be returned ordered using the ORDER BY clause in ascending or descending order. Elements in your array use none. When you pass the array as a parameter for the WHERE IN clause MySQL doesn't care about the order of the elements as you can see.
Fortunately there is a solution :)
First you will have to use Doctrine's ability to create a table of results indexed with what you want. Use this:
Doctrine::getTable('TbArticle')->createQuery('a INDEX BY id')->...;
This will return an array of results where the array keys are the id's of the rows. Then you can rearange the results array to match your $res (assuming that $rows has the rows returned by Doctrine):
foreach ($res as $i) {
$new_array[] = $rows[$i];
}
The tricky part is to make it work with the paginator. But I'm sure you can do that as well (try to retrieve the results from the paginator and rearange them before displaying).
I am trying to create a feature which essentially amounts to a Facebook style newsfeed. In order to order this newsfeed, I call and get all the information associated with all existing "stories" and orders them based on time.
However, I want to reorder these "stories" based on the outcome of a subsequent PHP call. How would you suggest that I go about this? I am really lost right now, so anything that could get me within the ball park would be great!
PHP usort might be what you're looking for:
<?php
function cmp($a, $b)
{
if ($a->somefield == $b->somefield) {
return 0;
}
return ($a->somefield < $b->somefield) ? -1 : 1;
}
$feeds = getFeeds();
usort($feeds, "cmp");
?>
http://php.net/manual/en/function.usort.php