Getting Highers and Same score in array - php

$Ascore = 30;
$Bscore = 30;
$Cscore = 20;
$Dscore = 20;
$score = array(
'As' => $Ascore,
'Bs' => $Bscore,
'Cs' => $Cscore,
'Ds' => $Dscore
);
$match = 0;
foreach($score as $key => $val){
if($val > $match){
$match = $val;
}
}
echo $match;
my intention is to find highers score that match , for example highers score = 30 ,As and Bs matched , echo out As = 30 , Bs = 30. so if any 2 of the highers score in the array and having the same highers score, echo both of them. only echo them out if they have same highers score.

Try the following:
$scores = [
'As' => $Ascore,
'Bs' => $Bscore,
'Cs' => $Cscore,
'Ds' => $Dscore,
];
$highest = max($scores);
foreach ($scores as $key => $val)
if ($val === $highest)
echo $key . ' = ' . $val . ', ';
Alternate if the trailing comma IS an issue:
$highest = max($scores);
$victors = [];
foreach ($scores as $key => $val)
if ($val === $highest)
$victors[] = $key . ' = ' . $val;
echo implode(', ', $victors);

Related

String array to print one by one

$products = Array ( [products] => Array ( [0] => 12,11,10 [1] => 16,15,14 [2] => 600,103,20 ) );
foreach($products as $k=>$v)
{
$product_id = $v[0];
$product_weight_id = $v[1];
$product_quantity = $v[2];
}
output required like:
12 16 600
11 15 103
10 14 20
current output :
12,11,10 16,15,14 600,103,20
Update:
If you want to generate a different output, next example may help:
PHP:
<?php
$products = array(
'12,11,10',
'16,15,14',
'600,103,20'
);
$output = array();
foreach($products as $product) {
$a = explode(',', $product);
foreach ($a as $key => $value) {
$output[$key][] = $value;
}
}
foreach($output as $line) {
echo implode(' ', $line)."<br>";
}
?>
Output:
12 16 600
11 15 103
10 14 20
Original answer:
Next example demonstrates two possible approaches to get an output from your array.
PHP:
<?php
$products = array(
'12,11,10',
'16,15,14',
'600,103,20'
);
// Complex approach
foreach($products as $product) {
$a = explode(',', $product);
foreach ($a as $value) {
echo $value." ";
}
echo "<br>";
}
// Simple approach
foreach($products as $product) {
echo $product."<br>";
}
?>
Output:
12 11 10
16 15 14
600 103 20
12,11,10
16,15,14
600,103,20
Please see below code.
$products = array (
'0' => '12,11,10',
'1' => '16,15,14',
'2' => '600,103,20'
);
$productIds = array();
$productWeights = array();
$productQuantities = array();
foreach( $products as $k => $v ) {
$line = explode(',', $v );
$productIds[] = $line[0];
$productWeights[] = $line[1];
$productQuantities[] = $line[2];
}
echo implode( ' ', $productIds);
echo '<br />';
echo implode( ' ', $productWeights);
echo '<br />';
echo implode( ' ', $productQuantities);
echo '<br />';
Using array_map() and implode() you can do it easily. Example:
$products = [[12,11,10], [16,15,14], [600,103,20]];
echo implode('<br />', array_map(function ($arr) { return implode(' ', $arr); }, $products));
Working demo.

Accurately setting up a ranking from an single dimension array

I would like to display some array data in relation to a competition, each player is ranked by the number of points they have, however if a player has the same amount of points to somebody else they should both have the exact same ranking position.
For instance...
1st Bob 500pts
2nd Joe 350pts
3rd Tom 250pts
3rd Tim 250pts
5th Jay 100pts
In this instance, as Tom & Tim have the exact same number of points they should be joint third, making the next person down 5th (rather than 4th), can anyone suggest the best way to achieve this with a simple array similar to follows
array('Bob' => 500, 'Joe' => '350', 'Tom' => '250', 'Tim' => '250', 'Jay' => '100');
Can anyone suggest the 'cleanest' solution for achieving this
This code will work for you:
$array = array('Bob' => 500, 'Joe' => '350', 'Tom' => '250', 'Tim' => '250', 'Jay' => '100');
arsort($array, SORT_NUMERIC);
$previousPoints = null;
$position = $total = 1;
foreach($array as $name=>$points) {
if ($points != $previousPoints) {
$position = $total;
}
echo $position.' '.$name.' '.$points."\n";
$previousPoints = $points;
$total++;
}
Online demo here.
$ar = array(
'Bob' => 500,
'Tim' => '250',
'Joe' => '350',
'Tom' => '250',
'Jay' => '100'
);
arsort($ar, SORT_NUMERIC);
$i = 1;
$previous = 1;
$previousPosition = 1;
foreach($ar as $k => $v)
{
if($v === $previous)
{
//If the value now is the same as the previous value use the previous position
echo "Position: $previousPosition, $k : $v <br />";
}
else
{
echo "Position: $i, $k : $v <br />";
}
//Previous value
$previous = $v;
//Previous Position
$previousPosition = $i;
//Always increment the value
$i++;
}
Try below code:
$a = array('Bob' => 500, 'Joe' => '350', 'Tom' => '250', 'Tim' => '250', 'Jay' => '100');
arsort($a);
$rank = 1;
$index = 1;
$prevUserPoints = 0;
foreach($a as $name=>$points) {
if($points != $prevUserPoints) {
$rank = $index;
}
$index++;
echo $rank . ' ' . $name . ' ' . $points . "\n";
$prevUserPoints = $points;
}
For displaying 1 as 1st, 2 as 2nd etc, you can use something like below:
function ordSuffix($n) {
$str = "$n";
$t = $n > 9 ? substr($str,-2,1) : 0;
$u = substr($str,-1);
if ($t==1) return $str . 'th';
else switch ($u) {
case 1: return $str . 'st';
case 2: return $str . 'nd';
case 3: return $str . 'rd';
default: return $str . 'th';
}
}
example: echo ordSuffix(23); This prints 23rd
Just a basic and alternative point of view you might want to consider.
$arr = [
"Joe" => "350",
"Tom" => "250",
"Jay" => "200",
"Tim" => "250",
"Bob" => "500",
"John" => "250" ,
"Paul" => "251.40"
];
$rank = array();
array_walk($arr,function($v, $k) use (&$rank)
{
if(isset($rank[$v]))
{
$rank[$v][$k] = $v;
asort($rank[$v]); //alphabetical order John, Tim, Tom
} else
{
$rank[$v] = array($k => $v);
}
});
krsort($rank);
var_dump(array_values($rank));

Imploding with "and" in the end?

I have an array like:
Array
(
[0] => Array
(
[kanal] => TV3+
[image] => 3Plus-Logo-v2.png
)
[1] => Array
(
[kanal] => 6\'eren
[image] => 6-eren.png
)
[2] => Array
(
[kanal] => 5\'eren
[image] => 5-eren.png
)
)
It may expand to several more subarrays.
How can I make a list like: TV3+, 6'eren and 5'eren?
As array could potentially be to further depths, you would be best off using a recursive function such as array_walk_recursive().
$result = array();
array_walk_recursive($inputArray, function($item, $key) use (&$result) {
array_push($result, $item['kanal']);
}
To then convert to a comma separated string with 'and' separating the last two items
$lastItem = array_pop($result);
$string = implode(',', $result);
$string .= ' and ' . $lastItem;
Took some time but here we go,
$arr = array(array("kanal" => "TV3+"),array("kanal" => "5\'eren"),array("kanal" => "6\'eren"));
$arr = array_map(function($el){ return $el['kanal']; }, $arr);
$last = array_pop($arr);
echo $str = implode(', ',$arr) . " and ".$last;
DEMO.
Here you go ,
$myarray = array(
array(
'kanal' => 'TV3+',
'image' => '3Plus-Logo-v2.png'
),
array(
'kanal' => '6\'eren',
'image' => '6-eren.png'
),
array(
'kanal' => '5\'eren',
'image' => '5-eren.png'
),
);
foreach($myarray as $array){
$result_array[] = $array['kanal'];
}
$implode = implode(',',$result_array);
$keyword = preg_replace('/,([^,]*)$/', ' & \1', $implode);
echo $keyword;
if you simply pass in the given array to implode() function,you can't get even the value of the subarray.
see this example
assuming your array name $arr,codes are below
$length = sizeof ( $arr );
$out = '';
for($i = 0; $i < $length - 1; $i ++) {
$out .= $arr [$i] ['kanal'] . ', ';
}
$out .= ' and ' . $arr [$length - 1] ['kanal'];
I think it would work to you:
$data = array(
0 =>['kanal' => 'TV1+'],
1 =>['kanal' => 'TV2+'],
2 =>['kanal' => 'TV3+'],
);
$output = '';
$size = sizeof($data)-1;
for($i=0; $i<=$size; $i++) {
$output .= ($size == $i && $i>=2) ? ' and ' : '';
$output .= $data[$i]['kanal'];
$output .= ($i<$size-1) ? ', ' : '';
}
echo $output;
//if one chanel:
// TV1
//if two chanel:
// TV1 and TV2
//if three chanel:
// TV1, TV2 and TV3
//if mote than three chanel:
// TV1, TV2, TV3, ... TV(N-1) and TV(N)
$last = array_slice($array, -1);
$first = join(', ', array_slice($array, 0, -1));
$both = array_filter(array_merge(array($first), $last));
echo join(' and ', $both);
Code is "stolen" from here: Implode array with ", " and add "and " before last item
<?php
foreach($array as $arr)
{
echo ", ".$arr['kanal'];
}
?>

How to extract array Keys to String in an array PHP

I need to extract a associative array keys into a string and implode with "/" or any character/symbols.
For eg:
$array = array([key1] =>
array([key11] =>
array([key111] => 'value111',
[key112] => 'value112',
[key113] => 'value113',
),
),
);
I need an output as below array:
array([0] => 'key1/key11/key111',[1] => 'key1/key11/key112', [2] => 'key1/key11/key112');
I've edited an answer given here and came up with the following code.
function listArrayRecursive($someArray, &$outputArray, $separator = "/") {
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($someArray), RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $k => $v) {
if (!$iterator->hasChildren()) {
for ($p = array(), $i = 0, $z = $iterator->getDepth(); $i <= $z; $i++) {
$p[] = $iterator->getSubIterator($i)->key();
}
$path = implode($separator, $p);
$outputArray[] = $path;
}
}
}
$outputArray = array();
listArrayRecursive($array, $outputArray);
print_r($outputArray);
Input:
Array
(
[key1] => Array
(
[key11] => Array
(
[key111] => value111
[key112] => value113
[key113] => value113
)
)
)
Output:
Array
(
[0] => key1/key11/key111
[1] => key1/key11/key112
[2] => key1/key11/key113
)
Works for different depth of array:
function getKeys($array, $prefix='', $separator = '/') {
$return = array();
foreach($array as $key => $value) {
if (!is_array($value)) $return[] = $prefix . $key;
else $return = array_merge($return, getKeys($value, $prefix . $key . separator), $separator);
}
return $return;
}
$keys = getKeys($array, '', '#');
See online fiddle http://ideone.com/krU4Xn
you could do something like...
$mapArray = array();
$symbol = '/';
foreach($array as $k =>$v)
foreach($v as $k1 =>$v1)
foreach($v1 as $k2 =>$v2)
$mapArray[] = $k.$symbol.$k1.$symbol.$k2;
also this obviously only works in this particular case, if it needs to be more generic it can be done, but I think this should get you started.

Split an array in sub arrays of consecutive dates

For a rent application, I have an array $dates like this:
Array
(
[2013-07-19] => 1
[2013-07-21] => 3
[2013-07-23] => 2
[2013-07-24] => 4
[2013-07-25] => 4
[2013-07-26] => 2
[2013-07-27] => 2
[2013-07-30] => 3
[2013-07-31] => 1
)
The date is the key, and the values are the number of items rent in that day for a specific product
How can I split this array in many sub arrays containing each a list of consecutive days?
Like this:
Array
(
[0] => Array
(
[2013-07-19] => 1
)
[1] => Array
(
[2013-07-21] => 3
)
[2] => Array
(
[2013-07-23] => 2
[2013-07-24] => 4
[2013-07-25] => 4
[2013-07-26] => 2
[2013-07-27] => 2
)
[3] => Array
(
[2013-07-30] => 3
[2013-07-31] => 1
)
)
$newArray = array();
foreach ($array as $date => $value)
{
// Make sure the newArray starts off with at least one element
if (empty($newArray))
$newArray[] = array();
// Calculate the difference in dates.
// (I like using DateTime, but use whichever method you like)
$dateTime = new DateTime($date);
$lastDateTime = new DateTime($lastDate);
$dateDiff = $dateTime->diff($lastDateTime);
// Add a new array to the end if the difference between this element and the last was more than a day
if ($dateDiff->days > 1)
$newArray[] = array();
// We can now be guaranteed that the last element of $newArray is the one we want to append to
$newArray[count($newArray) - 1][$date] = $value;
// Keep track of the last date you saw
$lastDate = $date;
}
Here it is in action: https://eval.in/38039
$newArray = array();
$i = 0;
foreach ($array as $date => $key) {
$thisDay = end(explode('-', $date));
$nextDay = end(explode('-', next($array[$date])));
if ($thisDay + 1 != $nextDay + 0)
$i++;
if (!isset($newArray[$i])) {
$newArray[$i] = array($date => $key);
} else {
if (!isset($newArray[$i][$date])) {
$newArray[$i][$date] = $key;
} else {
$newArray[$i][$date] = $key;
}//END IF
}//END IF
}//END FOREACH LOOP
This is the code i would use to do what you are asking.
UPDATE:
I was wrong above. i have altered the code to work this time:
$newArray = array();
$i = 0;
foreach ($array as $date => $key) {
$thisDay = end(explode('-', $date));
$nextDay = array_key_exists(date('Y-m-d', strtotime($date . ' +1 day')), $array);
if (!isset($newArray[$i])) {
$newArray[$i] = array($date => $key);
} else {
if (!isset($newArray[$i][$date])) {
$newArray[$i][$date] = $key;
} else {
$newArray[$i][$date] = $key;
}//END IF
}//END IF
if (!$nextDay)
$i++;
}//END FOREACH LOOP
Here is my test case:
<?php
$array = array(
'2013-07-19' => 1,
'2013-07-21' => 3,
'2013-07-23' => 2,
'2013-07-24' => 4,
'2013-07-25' => 4,
'2013-07-26' => 2,
'2013-07-27' => 2,
'2013-07-30' => 3,
'2013-07-31' => 1
);
echo '<pre>' . print_r($array, true) . '</pre>';
$newArray = array();
$i = 0;
foreach ($array as $date => $key) {
$thisDay = end(explode('-', $date));
$nextDay = array_key_exists(date('Y-m-d', strtotime($date . ' +1 day')), $array);
if (!isset($newArray[$i])) {
$newArray[$i] = array($date => $key);
} else {
if (!isset($newArray[$i][$date])) {
$newArray[$i][$date] = $key;
} else {
$newArray[$i][$date] = $key;
}//END IF
}//END IF
if (!$nextDay)
$i++;
}//END FOREACH LOOP
echo '<pre>' . print_r($newArray, true) . '</pre>';
?>
you can do it like this:
$data = array(
'2013-07-19' => 1,
'2013-07-21' => 3,
'2013-07-23' => 2,
'2013-07-24' => 4,
'2013-07-25' => 4,
'2013-07-26' => 2,
'2013-07-27' => 2,
'2013-07-30' => 3,
'2013-07-31' => 1
);
$result = array();
$ref = new DateTime('1821-11-11');
foreach ($data as $datum => $nb) {
if ($ref->add(new DateInterval('P1D'))->format('Y-m-d')!=$datum) {
$result[] = array();
$ref = new DateTime($datum);
}
$result[array_pop(array_keys($result))][$datum] = $nb;
}
print_r($result);

Categories