I have an array that goes from '00:00:00' to '23:59:59', something like this ['00:00:00', '00:00:01' ... '23:59:59'].
I need to write a function to reduce the array length into n items but always keeping the first and the last element.
An example:
reduce_into($array, 3) -> ['00:00:00', '12:00:00', '23:59:59']
Note that the array must be "balanced", that means that when I reduce it into 3 elements it will return the first, the one in the middle and the last one.
Here's the code:
function getnewarray($t,$i)
{
$newArr[0] = $t[0];
$a = 1;
$masterdivby = $divby = count($t) / ($i-1);
$ni = $i-2;
while($a <= $ni)
{
$newArr[$a] = $t[$divby];
$divby = $masterdivby + $divby;
$a++;
}
$newArr[$i] = $t[count($t) - 1];
return $newArr;
}
?>
Related
Hi,
i have a problem to solve. i tired but not get the result good result
please ignore if i make a mistake in question.
Here is problem
My Approch
$nwe = ["5","2","C","D","+"];
$test = 0;
$last =[];
for ($i = 0; $i < sizeof($nwe); $i++) {
$last[] .= $nwe[$i];
$end = end($last);
if($end === "C"){
$t = prev($last);
$b = array_reverse(array_keys($nwe,$t));
if (( array_search($end, $nwe)) !== false) {
unset($nwe[$b[0]]);
array_pop($nwe);
}
}
if($end === "+"){
$test += prev($last);
$test += prev($last);
$nwe[$i] = $test;
}
if($end === "D"){
$t = 2;
$t *= prev($last);
$nwe[$i] = $t;
}
}
echo "<pre>";
print_r($last);
print_r($test);
print_r(array_sum($nwe));
echo "</pre>";
My Result
Help me to out from this.
It looks like some test to see how good you know your PHP functions. You need a few to solve this the easy way:
is_numeric() and (int) for the numbers. (link and link)
array_pop() to remove the last array entry. (link)
array_slice() to retrieve the last two elements of the array. (link)
array_sum() to get the total of all array numbers. (link)
end() to get the last value of an array. (link)
This is the above applied:
$nwe = ["5","-2","4","C","D","9","+","+","-"];
$result=[];
//LOOP the array
foreach($nwe as $v){
// IS IT A NUMBER ? (add number)
if(is_numeric($v)){
// just shove the number in $result
$result[]=(int)$v;
continue;
}
//IS IT + ? (sum of last two)
if($v==='+'){
//get last TWO entries from $result. (returns an array)
$last=array_slice($result,-2);
//sum of $lasttwo
$result[]=array_sum($last);
continue;
}
//IS IT C ? (remove last)
if($v==='C'){
//remove the last entry from $result
array_pop($result);
continue;
}
//IS IT D ? (last * 2)
if($v==='D'){
//get last entry from $result
$last=end($result);
$result[]=$last*2;
continue;
}
}
//get the TOTAL
$total=array_sum($result);
echo implode(', ',$result).' = '.$total;
<?php
$fact_BB = array("[start]", "[mid]", "[end]");
$fact_HTML = array("<tr><td class='FactsTableTDOne'><p>", "</p></td><td class='FactsTableTDTwo'><p>", "</p></td></tr>");
$str_Facts = str_replace($fact_BB, $fact_HTML, $row['facts']);
echo $str_Facts;
?>
Is it possible to switch between 2 $fact_HTML?
1. $fact_HTMLone = "code";
2. $fact_HTMLtwo = "code";
3. $fact_HTMLone = "code";
4. $fact_HTMLtwo = "code";
5. $fact_HTMLone = "code";
etc. etc.
Sure. With $fact_HTML[0], $fact_HTML[1], $fact_HTML[n] etc. you can access your $fact_HTML array. Using modulo of 2 you can always access every 2nd (or first and second) elements of the array.
To check if the element is even or odd you can use:
if ($n % 2 == 0) {
//even element
} else {
//odd element
}
Also you can use Modulo 2 ($n % 2) as n to iterate through the array in the same way. You can also combine both variants.
$count = 10; //number of facts
for ($n = 0; $n < $count; $n++) {
$fact_HTML[$n % 2] = $fact;
}
What you want to achieve is a replace of some strings. I'd suggest a solution like this:
<?php
$str_Facts = $row['facts'];
$replacements = array( "[start]" => "<tr><td class='FactsTableTDOne'><p>",
"[mid]" => "</p></td><td class='FactsTableTDTwo'><p>",
"[end]" => "</p></td></tr>" );
foreach ($replacements as $repkey => $repval) {
$str_Facts = str_replace($repkey,$repval,$str_Facts);
}
echo $str_Facts;
?>
If you want to go on with your approach, you'd loop through the arrays (you have to ensure that the both arrays have the same number of elements).
<?php
$str_Facts = $row['facts'];
for ($i=0;$i<count($fact_BB);$i++) {
//if you want to switch every uneven, do this:
if ($i%2!=0) continue;
$str_Facts = str_replace($fact_BB[$i],$fact_HTML[$i],$str_Facts);
}
echo $str_Facts;
?>
Given the following array:
$arr = array(0,0,1,2,2,5,6,7,7,9,10,10);
And assuming $n = 2, what is the most efficient way to get a count of each value in the array within $n of each value?
For example, 6 has 3 other values within $n: 5,7,7.
Ultimately I'd like a corresponding array with simply the counts within $n, like so:
// 0,0,1,2,2,5,6,7,7,9,10,10 // $arr, so you can see it lined up
$count_arr = array(4,4,4,4,4,3,3,4,4,4, 2, 2);
Is a simple foreach loop the way to go? CodePad Link
$arr = array(0,0,1,2,2,5,6,7,7,9,10,10);
$n = 2;
$count_arr = array();
foreach ($arr as $v) {
$range = range(($v-$n),($v+$n)); // simple range between lower and upper bound
$count = count(array_intersect($arr,$range)); // count intersect array
$count_arr[] = $count-1; // subtract 1 so you don't count itself
}
print_r($arr);
print_r($count_arr);
My last answer was written without fully groking the problem...
Try sorting the array, before processing it, and leverage that when you run through it. This has a better runtime complexity.
$arr = array(0,0,1,2,2,5,6,7,7,9,10,10);
asort($arr);
$n = 2;
$cnt = count($arr);
$counts = array_pad(array(), $cnt, 0);
for ($x=0; $x<$cnt; $x++) {
$low = $x - 1;
$lower_range_bound = $arr[$x]-$n;
while($low >= 0 && ($arr[$low] >= $lower_range_bound)) {
$counts[$x]++;
$low--;
}
$high = $x + 1;
$upper_range_bound = $arr[$x]+$n;
while($high < $cnt && $arr[$high] <= $upper_range_bound) {
$counts[$x]++;
$high++;
}
}
print_r($arr);
print_r($counts);
Play with it here: http://codepad.org/JXlZNCxW
I have a loop like this
$rr=array();
foreach($relations as $key=>$type){
$rr[$relationType->U2U_Related_USR_ID]=$type[$k]->MSTT_Name.' / '.$type[$k+1]->MSTT_Name;
$k++;
}
Am getting only first index value. how to concatenate two index values in for each.
Increment by 2 !
$rr = array();
for ($i = 0, $n = count($type); $i < $n; $i += 2) {
$t1 = $type[$i];
$t2 = $type[$i + 1];
$rr[$relationType->U2U_Related_USR_ID] = $t1->MSTT_Name.' / '.$t2->MSTT_Name;
}
Note: $type's length should be an even number!
you can work with 2 couples key/value inside your loop like this :
foreach($relations as $key=>$type){
list( $odd_key, $odd_value ) = each( $relations );
//... your code here
// This work with a step by 2 elements. If you need step by 1,
// add the following line at the end of the loop :
//prev( $relations )
}
I have an array having three element $base =(#m, #f,#p)
I have a second array having any number of element like $var = (s1, s2)
Now i need to create all possible combinations depending only on the base array. The formula I found is x pow y.
In this example my base array has three element and $var has 2, so pow(3, 2) is 9. I need these nine combinations. i.e
#m#m #m#f #m#p
#f#m #f#f #f#p
#p#m #p#f #p#p
The number of elements in the 2nd array is in effect the length of the generated combinations. As in this example the length of the 2nd array is 2 so all generated strings have length 2.
You can use a recursive function like this:
// input definition
$baseArray = array("#m", "#f", "#p");
$varArray = array("s1", "s2", "s3");
// call the recursive function using input
$result = recursiveCombinations($baseArray, sizeof($varArray));
// loop over the resulting combinations
foreach($result as $r){
echo "<br />combination " . implode(",", $r);
}
// this function recursively generates combinations of #$level elements
// using the elements of the $base array
function recursiveCombinations($base, $level){
$combinations = array();
$recursiveResults = array();
// if level is > 1, get the combinations of a level less recursively
// for level 1 the combinations are just the values of the $base array
if($level > 1){
$recursiveResults = recursiveCombinations($base, --$level);
}else{
return $base;
}
// generate the combinations
foreach($base as $baseValue){
foreach($recursiveResults as $recursiveResult){
$combination = array($baseValue);
$combination = array_merge($combination, (array)$recursiveResult);
array_push($combinations, $combination);
}
}
return $combinations;
}
Working codepad demo
<?php
$strs = Array("some", "thing", "here");
$poss = Array(1, 2);
$new = Array();
for($i = 0; $i < pow(count($strs), count($poss)); $i++) {
for($j = 0; $j < count($strs); $j++) {
$new[$i] = $strs[($i%count($strs))] . " " . $strs[$j];
}
}
print_r($new);
?>
Working codepad link(for given example).
LINKS
pow(4, 3)
pow(4, 2)
pow(3, 5)