You are here: sorting an associative array of objects by value? « PHP Programming Language « IT news, forums, messages
sorting an associative array of objects by value?

Posted by Greg D on 12/13/06 00:08

Hi all,

I'm trying to sort an array of objects within an object. Included is a
dumbed down example so that we can get at the meat of the issue without
worrying about complexity or validation. Basically, Funk is an object that
has a name (string) and a value(int). FunkThis represents an object
containing a list of Funks, with each key corresponding to the name of the
Funk. I want to sort this list by val, but I get a Warning: usort():
Invalid comparison function error when I run the script. Keep in mind that
this is for PHP 4

I'm open to suggestions to getting this to work.



<?php

class Funk {

var $name;
var $val;

function Funk($name,$val) {
$this->name = $name;
$this->val = $val;
}

function getVal() {
return $this->val;
}

function getName() {
return $this->name;
}
}

class FunkThis {

var $list;

function FunkThis() {
$this->list = null;
}

function add($funk) {
$this->list[$funk->getName()] = $funk;
}

function compareFunks($a,$b) {
$aVal = $a->getVal();
$bVal = $b->getVal();
if ($aVal == $bVal) return 0;
if ($aVal > $bVal) return 1;
if ($aVal < $bVal) return -1;

}

function sortByFunk() {
$list = $this->list;
$this->list = uasort($list,"compareFunks");
}

function show() {
print_r($this->list);
}
}

$a = new Funk("A",3);
$b = new Funk("B",7);
$c = new Funk("C",1);
$d = new Funk("D",9);
$e = new Funk("E",6);

$funkthat = new FunkThis();

$funkthat->add($a);
$funkthat->add($b);
$funkthat->add($c);
$funkthat->add($d);
$funkthat->add($e);

$funkthat->sortByFunk();

$funkthat->show();
?>

Greg

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация