I just tried out this code below and it doesn't seem to work. I corrected the bugs and it doesn't show nothing. It should show the standings array which I can then make it into a table. It's for Joomla MVC component that I'm working on. Can maybe somebody help me?
Thanks!
The code: EDIT:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('home' , 'scoreHome' , 'away' , 'scoreAway')));
$query->from($db->quoteName('futliga_pc_liga1'));
$db->setQuery($query);
$rows = $db->loadAssocList();
$standings = array ();
$standingTemplate = array ('matches' => 0, 'wins' => 0, 'draws' => 0, 'losses' => 0, 'scoreHome' => 0, 'scoreAway' => 0, 'goalsdiff' => 0, 'points' => 0);
foreach ($rows as $row) {
handleMatch($row['home'], $row['scoreHome'], $row['scoreAway']);
handleMatch($row['away'], $row['scoreAway'], $row['scoreHome']);
echo '<pre>';
print_r( usort($standings, 'comparePoints' ) );
}
function handleMatch($team, $scoreHome, $scoreAway){
global $standings, $standingTemplate;
if ($scoreHome > $scoreAway)
{
$points = 3;
$win = 1;
$draw = 0;
$loss = 0;
}
elseif ($scoreHome == $scoreAway)
{
$points = 1;
$win = 0;
$draw = 1;
$loss = 0;
}
else
{
$points = 0;
$win = 0;
$draw = 0;
$loss = 1;
}
if ( empty($standings[$team])){
$standing = $standingTemplate;
} else {
$standing = $standings[$team];
$standingTemplate['matches']++;
$standingTemplate['wins'] += $win;
$standingTemplate['draws'] += $draw;
$standingTemplate['losses'] += $loss;
$standingTemplate['scoreHome'] += $scoreHome;
$standingTemplate['scoreAway'] += $scoreAway;
$standingTemplate['goalsdiff'] += $scoreHome - $scoreAway;
$standingTemplate['points'] += $points;
}
$standings[$team] = $standing;
}
function comparePoints($a, $b){
if ($a['points'] == $b['points']) {
if ($a['goalsdiff'] == $b['goalsdiff']) return 0;
return ($a['goalsdiff'] < $b['goalsdiff']) ? 1 : -1 ;
}
return ($a['points'] < $b['points']) ? 1 : -1 ;
}
You are printing result of usort which is a boolean value. If you expect an array representation, then print the array itself:
usort($standings, 'comparePoints');
print_r($standings);
Related
I am trying to sort an array based on a column value:
Example:
$cats[0]['holders'] = 55;
$cats[1]['holders'] = 66;
$cats[2]['holders'] = 77;
$cats[3]['holders'] = 23;
$cats[4]['holders'] = 64;
$cats[5]['holders'] = 82;
$cats[6]['holders'] = -3;
$cats[7]['holders'] = -5;
$cats[8]['holders'] = -17;
$cats[9]['holders'] = -25;
$cats[10]['holders'] = 66;
$cats[11]['holders'] = -10;
$cats[12]['holders'] = 0;
$cats[13]['holders'] = 5;
$cats[14]['holders'] = 4;
$cats[15]['holders'] = -3;
function compareHolders($a, $b) {
$aPoints = $a['holders'];
$bPoints = $b['holders'];
return strcmp($aPoints, $bPoints);
}
$cats = usort($cats, 'compareHolders');
I would like to get the top 5 values and bottom 5 values:
$first_5_tokens = array_slice($tokens, 0, 5, true);
print_r($first_5_tokens);
$last_5_tokens = array_slice($tokens, -5);
print_r($last_5_tokens);
This is not sorting the array for me by "holder" value. How can I do this? Thanks!
Your comparison function sorts array in descending order and also, don't use it like - $cats = usort($cats, 'compareHolders'); Instead just use it like - usort($cats, 'compareHolders');
I changed your function and did it like this.
$cats[0]['holders'] = 55;
$cats[1]['holders'] = 66;
$cats[2]['holders'] = 77;
$cats[3]['holders'] = 23;
$cats[4]['holders'] = 64;
$cats[5]['holders'] = 82;
$cats[6]['holders'] = -3;
$cats[7]['holders'] = -5;
$cats[8]['holders'] = -17;
$cats[9]['holders'] = -25;
$cats[10]['holders'] = 66;
$cats[11]['holders'] = -10;
$cats[12]['holders'] = 0;
$cats[13]['holders'] = 5;
$cats[14]['holders'] = 4;
$cats[15]['holders'] = -3;
foreach($cats as $cat) {
echo $cat['holders'] . "<br>";
}
// function compareHolders($a, $b) {
//
// $aPoints = $a['holders'];
// $bPoints = $b['holders'];
//
// return strcmp($aPoints, $bPoints);
//
// }
function compareHolders($a, $b) {
$a = $a['holders'];
$b = $b['holders'];
if ($a == $b)
return 0;
return ($a > $b) ? -1 : 1;
}
usort($cats, 'compareHolders');
echo "<h4>After</h4>\n";
foreach($cats as $cat) {
echo $cat['holders'] . "<br>";
}
// print_r($cats);
$tokens = $cats;
echo "<h4>First Five</h4>\n";
$first_5_tokens = array_slice($tokens, 0, 5, true);
print_r($first_5_tokens);
echo "<h4>Last Five</h4>\n";
$last_5_tokens = array_slice($tokens, -5);
print_r($last_5_tokens);
I have a list of number in array. Here's my example data:
Person 1 => 20, 40, 50
Person 2 => 10, 20, 40
Person 3 => 20, 20, 30
I want to ask, how to put their scores to an array and calculate it by it index? My code to create this array:
$indeksarr = 1;
$temparr[$indeksarr] = array();
$num = 3;
while($grade = $query->fetch_array()) <-- basically get score from DB (only return score for each student)
{
for($i=1; $i <= $num; $i++)
{
$newdata = array($indeksarr => $grade);
$temparr[$indeksarr][] = $newdata;
$indeksarr++;
}
}
for($i=1; $i <= $num; $i++)
{
print_r($temparr[$i]);
}
My code result:
Result[1] = 20
Result[2] = 10
The result that I want:
Result[1] = 50 ( <- 20+10+20 ) <- all from array index 1
Result[2] = 80 ( <- 40+20+20 ) <- all from array index 2
Result[3] = 120 ( <- 50+40+30 ) <- all from array index 3
Any idea to fix my array?
Please try below code once, it might help for dynamic values also.
while ($grade = $query->fetch_array()) {
//$grdata = explode(",", $grade); // if those are comma separated values
$grdata = $grade;
for ($j = 0, $k = 1; $j < count($grdata); $j++, $k++) {
if (isset($temparr[$k])) {
$temparr[$k] = $temparr[$k] + $grdata[$j];
} else {
$temparr[$k] = $grdata[$j];
}
}
}
print_r($temparr);
biuld array like below
$persons = array('Person1'=>array(20,40,50),'Person2' => array(10, 20, 40),'Person3' => array(20, 20, 30));
//than perform below function
$array_sum = array_reduce($persons,"abb");
function abb($a,$b)
{
foreach($b as $key=>$value)
{
if(isset($a[$key]))
$a[$key] += $value;
else
$a[$key] = $value;
}
return $a;
}
var_dump($array_sum);
o/p
array (size=3)
0 => int 50
1 => int 80
2 => int 120
try this:
$result = array();
$start_index = 1;
$stop_index = 3;
while($grade = $query->fetch_array()) //<-- basically get score from DB (only return score for each student)
{
// grade = array('Person 1' => array(20,10,20));
$values = array_values($grade);
$result[$start_index] = array_sum($values[0]);
if ($start_index == $stop_index) break; // stop when it reach stop_index
$start_index++;
}
echo "<pre>";
print_r($result);
echo "</pre>";
die;
Here's a simple alternative using array_walk and array_sum:
$subTotal = [[0,0,0],[0,0,0],[0,0,0]];
$line = 0;
function walk($item, $key) {
global $subTotal;
global $line;
$subTotal[$key][$line] = $item;
}
$array = [
[20, 40, 50],
[10, 20, 40],
[20, 20, 30]
];
$finalArray = [];
array_walk($array[0], 'walk');
$line = 1;
array_walk($array[1], 'walk');
$line = 2;
array_walk($array[2], 'walk');
$finalArray[] = array_sum($subTotal[0]);
$finalArray[] = array_sum($subTotal[1]);
$finalArray[] = array_sum($subTotal[2]);
// Will print '50, 80, 120, '
foreach($finalArray as $total) {
echo $total.', ';
}
Hope this helps!
already look around but cant find what i want for PHP.
just say i have a number : 1234 ( can be splitted first into array )
and i want to get how many number combination possible for 2 digits, 3 digits , and 4 digits
for example :
possible 4 digits will be :
1234,1243,1324,1342, and so on. ( i dont know how many more )
possible 2 digits will be :
12,13,14,21,23,24,31,32,34,41,42,43
the closest one i get is :
$p = permutate(array('1','2','3','4'));
$result = array();
foreach($p as $perm) {
$result[]=join("",$perm);
}
$result = array_unique($result);
print join("|", $result);
function permutate($elements, $perm = array(), &$permArray = array()){
if(empty($elements)){
array_push($permArray,$perm); return;
}
for($i=0;$i<=count($elements)-1;$i++){
array_push($perm,$elements[$i]);
$tmp = $elements; array_splice($tmp,$i,1);
permutate($tmp,$perm,$permArray);
array_pop($perm);
}
return $permArray;
}
but how can i edit this so i can display for 3 and 2 digits ?
Thanks
i got what i want
it's from #mudasobwa link. and i edit to what i want.
<?php
$in = array(1,2,3,4,5,6);
$te = power_perms($in);
// print_r($te);
$thou=0;
$hun =0;
$pu = 0;
for($i=0;$i<count($te);$i++)
{
$jm = count($te[$i]);
for($j=0;$j<$jm;$j++)
{
$hsl[$i] = $hsl[$i] . $te[$i][$j];
}
if($hsl[$i] >=100 && $hsl[$i] < 1000 )
{
$ratus[$hun] = intval($hsl[$i]);
$hun = $hun + 1;
}
if($hsl[$i] <100 && $hsl[$i] >=10)
{
$pul[$pu] = intval($hsl[$i]);
$pu = $pu + 1;
}
if($hsl[$i] >=1000 && $hsl[$i] < 10000)
{
$th[$thou] = intval($hsl[$i]);
$thou = $thou + 1;
}
}
$th=array_unique($th);
$pul = array_unique($pul);
$ratus = array_unique($ratus);
sort($ratus);
sort($pul);
sort($th);
print_r($th);
function power_perms($arr) {
$power_set = power_set($arr);
$result = array();
foreach($power_set as $set) {
$perms = perms($set);
$result = array_merge($result,$perms);
}
return $result;
}
function power_set($in,$minLength = 1) {
$count = count($in);
$members = pow(2,$count);
$return = array();
for ($i = 0; $i < $members; $i++) {
$b = sprintf("%0".$count."b",$i);
$out = array();
for ($j = 0; $j < $count; $j++) {
if ($b{$j} == '1') $out[] = $in[$j];
}
if (count($out) >= $minLength) {
$return[] = $out;
}
}
// usort($return,"cmp"); //can sort here by length
return $return;
}
function factorial($int){
if($int < 2) {
return 1;
}
for($f = 2; $int-1 > 1; $f *= $int--);
return $f;
}
function perm($arr, $nth = null) {
if ($nth === null) {
return perms($arr);
}
$result = array();
$length = count($arr);
while ($length--) {
$f = factorial($length);
$p = floor($nth / $f);
$result[] = $arr[$p];
array_delete_by_key($arr, $p);
$nth -= $p * $f;
}
$result = array_merge($result,$arr);
return $result;
}
function perms($arr) {
$p = array();
for ($i=0; $i < factorial(count($arr)); $i++) {
$p[] = perm($arr, $i);
}
return $p;
}
function array_delete_by_key(&$array, $delete_key, $use_old_keys = FALSE) {
unset($array[$delete_key]);
if(!$use_old_keys) {
$array = array_values($array);
}
return TRUE;
}
?>
I have problem with $res array.... i don't know with $res[0] is like a empty variable (array have a lot of dates but i don't know why and where is wrong... i tried with $res['ItemSlotX'] and now with $res[0]...
Edited: i have already changed my $res[0] and 1 but is same...
Thank you for help!
function smartsearch($whbin,$itemX,$itemY) {
if (substr($whbin,0,2)=='0x') $whbin=substr($whbin,2);
$items = str_repeat('0', 240);
$itemsm = str_repeat('1', 240);
$i = 0;
while ($i<240) {
$_item = substr($whbin,(64*$i), 64);
$type = (hexdec(substr($_item,18,2))/16);
$dbgetvalutslots = new DB_MSSQL;
$dbgetvalutslots->Database='DTRMUWAP';
$dbgetvalutslots->query("Select [ItemSlotX],[ItemSlotY] from ItemDetails where ItemIndex = '".hexdec(substr($_item,0,2))."' and ItemGroup = '".$type."'");
$ijj=0;
$res=array();
while ($dbgetvalutslots->next_record()) {
$temp = array(
'ItemSlotX' => $dbgetvalutslots->f('ItemSlotX'),
'ItemSlotY' => $dbgetvalutslots->f('ItemSlotY')
);
$res[$ijj]=$temp;
$ijj++;}
$y = 0;
while($y<$res[1]) {
$y++;
$x=0;
while($x<$res[0]) {
$items = substr_replace($items, '1', ($i+$x)+(($y-1)*8), 1);
$x++;
}
}
$i++;
}$y = 0;
while($y<$itemY) {
$y++;$x=0;
while($x<$itemX) {
$x++;
$spacerq[$x+(8*($y-1))] = true;
}
}
$walked = 0;
$i = 0;
while($i<120) {
if (isset($spacerq[$i])) {
$itemsm = substr_replace($itemsm, '0', $i-1, 1);
$last = $i;
$walked++;
}
if ($walked==count($spacerq)) $i=119;
$i++;}$useforlength = substr($itemsm,0,$last);
$findslotlikethis='^'.str_replace('++','+',str_replace('1','+[0-1]+', $useforlength));
$i=0;$nx=0;$ny=0;
while ($i<120) {
if ($nx==8) { $ny++; $nx=0; }
if ((eregi($findslotlikethis,substr($items, $i, strlen($useforlength)))) && ($itemX+$nx<9) && ($itemY+$ny<16))
return $i;
$i++;
$nx++;
}
return 1337;}
There seems to be a lack of context for the code in order to really understand it, but for what I can see here already, it should be:
Edit: some extra code to be more explicit
$y = 0;
$numberOfRecords = count($res);
while($recordN < $numberOfRecords)
while($y<$res[$recordN]["ItemSlotY"]) {
$y++;
$x=0;
while($x<$res[$recordN]["ItemSlotX"]) {
$items = substr_replace($items, '1', ($i+$x)+(($y-1)*8), 1);
$x++;
}
}
$i++;
$recordN++;
}
as $temp is an array and you're then doing $res[$ijj]=$temp;
As the title states I'm searching for a unique solution in multi arrays. PHP is not my world so I can't make up a good and fast solution.
I basically get this from the database: http://pastebin.com/vYhFCuYw .
I want to check on the 'id' key, and if the array contains a duplicate 'id', then the 'aantal' should be added to each other.
So basically the output has to be this: http://pastebin.com/0TXRrwLs .
Thanks in advance!
EDIT
As asked, attempt 1 out of many:
function checkDuplicates($array) {
$temp = array();
foreach($array as $k) {
foreach ($array as $v) {
$t_id = $k['id'];
$t_naam = $k['naam'];
$t_percentage = $k['percentage'];
$t_aantal = $k['aantal'];
if ($k['id'] == $v['id']) {
$t_aantal += $k['aantal'];
array_push($temp, array(
'id' => $t_id,
'naam' => $t_naam,
'percentage' => $t_percentage,
'aantal' => $t_aantal,
)
);
}
}
}
return $temp;
}
How about this code, each 'aantal' has initial value of 1, and duplicated id have their aantal incremented mutually, and duplicated id's are not suppressed. As your first array index is 0-based numeric, so we don't consider this dimension as a hash array, but rather a normal array.
UPDATED: id's can be duplicated 2 times, 3 times, 4 times, ...
<?php
//
// duplicate elements are not suppressed:
//
function checkDuplicates($xarr) {
//
$xarrDone = array();
//
$n = count($xarr);
//
for($i = 0; $i < $n; $i++)
{
if(! isset($xarrDone[$i]))
{
$id0 = $xarr[$i]['id'];
$hasId0 = array();
for($j = $i + 1; $j < $n; $j++)
{
if($xarr[$j]['id'] == $id0)
{
$hasId0[] = $j;
}
}
$n1 = count($hasId0);
if($n1 > 0)
{
$xarr[$i]['aantal'] += $n1;
$xarrDone[$i] = true;
for($j = 0; $j < $n1; $j++)
{
$xarr[$hasId0[$j]]['aantal'] += $n1;
$xarrDone[$hasId0[$j]] = true;
}
}
}
}
//
return $xarr;
}
//
// duplicate elements are suppressed:
//
function checkDuplicates2Unique($xarr) {
//
$xarrDone = array();
$xarrNew = array();
//
$n = count($xarr);
//
for($i = 0; $i < $n; $i++)
{
if(! isset($xarrDone[$i]))
{
$id0 = $xarr[$i]['id'];
$hasId0 = array();
for($j = $i + 1; $j < $n; $j++)
{
if($xarr[$j]['id'] == $id0)
{
$hasId0[] = $j;
}
}
$n1 = count($hasId0);
if($n1 > 0)
{
$xarr[$i]['aantal'] += $n1;
for($j = 0; $j < $n1; $j++)
{
$xarrDone[$hasId0[$j]] = true;
}
}
$xarrNew[] = $xarr[$i];
$xarrDone[$i] = true;
}
}
//
return $xarrNew;
}
//
// main test:
//
$xarr0 = array(
array(
'id' => 6
, 'naam' => 'Aardmonnik'
, 'percentage' => '8,00%'
, 'aantal' => 1
)
, array(
'id' => 34
, 'naam' => 'Achel 8 Bruin'
, 'percentage' => '8,00%'
, 'aantal' => 1
)
, array(
'id' => 34
, 'naam' => 'Achel ppBruin'
, 'percentage' => '9,00%'
, 'aantal' => 1
)
, array(
'id' => 34
, 'naam' => 'Achel ppBruin'
, 'percentage' => '9,00%'
, 'aantal' => 1
)
, array(
'id' => 3
, 'naam' => 'IV Saison'
, 'percentage' => '6,5%'
, 'aantal' => 1
)
, array(
'id' => 34
, 'naam' => '3 Schténg'
, 'percentage' => '6,00%'
, 'aantal' => 1
)
);
//
echo "<pre>
Original:
";
print_r($xarr0);
//
echo "</pre>";
//
$xarr = checkDuplicates($xarr0);
//
echo "<pre>
Modified:
";
print_r($xarr);
//
$xarr = checkDuplicates2Unique($xarr0);
//
echo "<pre>
Modified Unique:
";
print_r($xarr);
//
echo "</pre>";
?>
?
checkDuplicates(): keep duplicated id's.
checkDuplicates2Unique(): delete duplicated id's to get unique id's.
Try using php's array_unique function: http://php.net/manual/en/function.array-unique.php
It should work on arrays
Otherwise (if you can sort the array -> faster):
<?php
$db = array(....); // your data
function remove_duplicates (array $arr) {
usort($arr, function ($a, $b) {
return $a['id'] < $b['id'];
});
$result = array();
$last_id = null;
$last_index = -1;
for ($i=0; $i<count($arr); ++$i) {
if ($arr[$i]['id'] == $last_id) {
result[$last_index]['aantai'] += 1;
continue;
}
$last_id = $arr[$i]['id'];
$last_index = count($result);
$result[] = $arr[$i];
}
return $result;
}
?>
Only loop over the input once, then copy the element when the id is new, else add the value:
function checkDuplicates($array) {
$temp = array();
// Only loop through the input once
foreach($array as $k) {
// Use the id as array index
if (array_key_exists($k['id'], $temp) {
// Only check id and add aantal?
$temp[$k['id']['aantal'] += $k['aantal'];
} else {
// Copy the element to the output
$temp[$k['id']] = $k;
}
}
return $temp;
}
Depending on your further code, you might need to reset the array indices by sort() or something.
Edit: sorry I forgot an index to $temp - the aantal field schould be correct now.