I'v got this array:
$by_date = array(
"2018-10-05"=>54,
"2018-10-07"=>20,
"2018-10-08"=>31,
"2018-10-12"=>52
);
I want to get value by date, but if the date doesn't exist get the lowest date value
for example:
if the date is "2018-10-07" I'll get 20
and if the date is "2018-10-10" I'll get 31
that can go to bigger differences between the date and the last key in the array
For example, if the date is "2019-01-25" I'll get 52 because "2018-10-12" is the last key in the array.
Thanks for the help :)
You guys where right the previews answer wasn't good enough
I'v made a work around that works for me, not sure about efficiency
if (!isset($by_date[$testVal])){
$by_date[$testVal] = null;
ksort($by_date);
$date_key = array_search($price_date,array_keys($by_date));
$by_date[$testVal] = (array_values($by_date)[$date_key-1]);
}
$by_date_price = $by_date[$testVal];
Thank you for the help and comments
You can do it with a simple if condition that uses isset() to check for your input as a key on the array. If the condition is met, you return the matched value, otherwise, use max() and array_keys() to return the value with the highest key.
$by_date = array(
"2018-10-05"=>54,
"2018-10-07"=>20,
"2018-10-08"=>31,
"2018-10-12"=>52
);
$testVal = '2018-10-12'
if (isset($by_date[$testVal]))
return $by_date[$testVal];
else
return $by_date[max(array_keys($by_date))];
Related
I have run into an issue where i am adding the point for a user with the previous point already stored in the table via laravel. Now I have an issue where i need to loop all the points of a specific user and I need to add in a new column for each entry the difference between the old previous point and the current point.
From the table i have first entry point is 1 , second entry point is 11, third is 21 and 4th is 22. Here what I need is, I need to loop all these data and for the first record i need to add the difference as 1 in new column and for second the difference between 1st and 2nd row are 10 and for 3rd the difference between 2nd and 3rd are again 10 and for 4th record th diff between the 3rd and 4th are 1.
Please someone provide me with a function which will help me to update new column with the difference in points based on previous and the current point
I assume you are using model
You can try this.
// $id is equal to user_id
function difference($id) {
// First get all your data
$data = YourModel::where('user_id', $id)->get();
// Loop all your data
foreach($data as $d) {
//get previous data
$last = YourModel::where('user_id',$id)->where('created_at', '<', $d->created_at)->first();
// if null then return zero else get the point
$last = isset($last) ? $last->points : 0;
// get the difference from the last
$dif = $d->points - $last;
// putting the difference to the data
$d->difference = $dif;
$d->save();
}
}
Hope this will help you...
I am working on an import script that needs to evaluate whether the set string fits with the possible values the backend field can have.
More exactly what I have is this array of committes:
$committees = array(
'Ämter' => 1,
'Abteilungen' => 2,
'Konservatoren' => 3,
'Dienstagssitzung' => 4,
);
and now I need to figure out if a string saved in
variable $category matches any key in that array. If it does match one of the entries, I need it to return the value (1, 2, 3 or 4) that goes with that key.
I read up about it here on Stackoverflow and found plenty examples to see if a value equals one in an array, for example:
preg_match array items in string?
and tried to follow those along.
I tried
$committeesKeys = '/(' . implode('|', array_keys($committees)) . ')/';
$matches = preg_match($committeesKeys, $category);
but that only returned how many matches it found?
I also tried
$input = preg_quote($category, '/');
$matches = preg_filter('/'.$input.'/', null, $committees);
as that was suggested somehwere else, can't find the link anymore, but that returned an empty array.
I am new to all of this so might be totally wrong here.
Can anybody tell me how I can do this, or where I can find an answer to the question? I might just not have found it, my brain is rather tired right now...
I feel that I have right to post that as answer accepted :-) :
echo (isset($committees[$category]))?$committees[$category]:'There is no '.$category.' category';
you can do something like this:
function getValue($category){
if (array_key_exists($category, $committees)){
return $committees[$category]; //the value you want
}
}
Hope this helps :)
preg_match() has a 3rd argument which will allow you to save capture groups into a numerical array. However, if you want to compare a string directly you can simply use a loop and strcmp or === which will probably work faster since preg_match has to compile the regex you define in the first argument. My solution for this problem would look like:
$found = FALSE;
foreach ( $committees as $name=>$number ) {
if ( $name === $category ) {
$found = $number;
}
}
return $found;
You make it difficult by not showing what is in the category matches.
Maybe something like this.
$results = array_intersect ($matches,$committees );
I have a two-dimensional array with two key values, [program] and [balance], created by a MySQL SELECT statement in WordPress. I know what the values of [program] will be (they never change) - it's the balances I'm interested in.
For example:
*[program] = 'Sales', [balance] = 10,000*
*[program] = 'Commission', [balance] = 1,250*
All I want to do is assign the balance value to a variable, so I will have:
*$sales = (the balance for the Sales program)*
*$commission = (the balance for the Commission program)*
I know I'm being thick here, but I cannot see how to do this after about an hour of searching and screwing around with php. It's a total brain block and all the references I can find online talk about loops and echoing all the values and stuff.
Would appreciate a de-blocking!
//make a function
function findBalanceByProgram($inputArray,$program)
//loop trough all the keys on the first dimension
foreach($inputArray as $val){
//check in the second dimension if your program is the same as the program you are checking for
if($val['program']==$program)
//if so.. return the value and jump out of the function
return $val['balance'];
}
}
//an example of use.
echo findBalanceByProgram($yourArray,'sales');
I am trying to check whether an entry exists (one or more) in our database. However, even when I know there are no entries, I am getting an array which has a first entry of zero. Therefore it is not empty and I am not getting what I need.
Here's my code:
<?php
$query = mysql_query("SELECT * FROM table WHERE column = $yfbid_number AND timestamp BETWEEN (NOW()- Interval 1 DAY) AND NOW()");
$array[] = array();
while ($row = mysql_fetch_assoc($query)){
$array[] = $row['column'];
}
?>
When doing print_r on an array which should be empty, I am getting: ( [0] => Array ( ) ) and therefore count is 1 and not zero, which messes up my code. Any ideas how to get to a truly empty array in this situation?
I'd rather not delete this entry but avoid it in the first place, because in most use cases I will get either an empty array or one that only has one entry (a real entry), in which case I will want to easily distinguish between the two. (as it is now, both give a count of 1 entry, which is very bad for our porpuses). Thanks.
Change:
$array[] = array();
to
$array = array();
With your version, if $array doesn't already exist, PHP will first create an array, then append an empty array to it. So you end up with a 1 element array whose only member is an empty array.
$array[] = array(); should be $array = array(). Right now, you are appending an array element to an array that is initialized. Turn notices on and you'll get a complaint about an undefined variable (probably).
I suggest you first do a SELECT COUNT(*) to determine how many entries you'll get. Then you KNOW that the result will be a useful answer, and can make or not make a subsequent query on the basis of your result.
If I have:
$mainarray = some array of things with some repeated values
$array_counted = array_count_values ($mainarray);
How can I find the maximum value in $array_counted?
(This would be the element that appeared most often in $mainarray I think. Its mostly a syntax issue as I am pretty sure I could loop it, but not sure of the syntax to use)
You can find first max value as
$main_array = array(1,2,3,4,5,6,6,6,6,6,6,6);
$max_val = max($main_array);
for find all of max vals
in php < 5.3
function findmax($val)
{
global $max_val;
return $val == $max_val;
}
$max_values_array = array_filter($main_array,'findmax');
in php >= 5.3
$max_values_array = array_filter($main_array,function($val) use ($max_val) { return $val == $max_val; });
echo count($max_values_array);
var_dump($max_values_array);
You could sort the array and take the first, respectively last item out of it, if you don't want to loop.
Since you associate the count with the values with that:
$array_counted = array_count_values ($mainarray);
You only need to sort it afterwards, and return the first key (which is the most occured element):
arsort($array_counted);
print key($array_counted); // returns first key
ok, the guy whos answer I used has deleted his comment so here is how I did it:
I used arsort($array_counted) to sort the array, while keeping index. rsort alone does not work as the result of array_count_values is an associative array. Thank you all.