问题描述
这里是我想做的:
$newArray = array();
foreach($student as $s){
$newArray[$s->id][$s->grade] = $s;
}
我想根据成绩对学生进行排序排序),但我只是想要排序不是id。我可以不这样:
I want to sort the students by their grades (more of a group than a sort) but I just want the grades to be sorted not the id. I could have don't this:
$newArray[$s->id] = $s->grade
asort($newArray)
但我需要 $ s
。
如何实现这样的排序?
推荐答案
编辑:
声明你的排序回调作为一个成员函数(当然在你需要它的同一个类中):
Sine you're working in a framework, best declare your sort callback as a member function (inside the same class as where you'll be needing it, of course):
private function sortCB(array $a, array $b)
{//the array type hinting in arguments is optional
$i = array_keys($a);//but highly recommended
$j = array_keys($b);
if (end($i) === end($j))
{
return 0;
}
//replace '>' with '<' if you want to sort descending
return (end($i) > end($j) ? 1 : -1);//this is ascending
}
uasort($theArray,array($this,'sortCB'));
有关更多示例,请参阅。我在这个(笨重的)答案的末尾添加了一个完整的例子
For more examples, see the docs. I've added a full class example at the end of this (bulky) answer
a href =http://writecodeonline.org/php> writecodeonline ,这不是所有太好的这种东西,但这是工作:
I've tried this on writecodeonline, which isn't all too good at this kind of stuff, but this did work:
$foo = array_fill_keys(array('foo','bar','q','Bond'),array());
$i = '256';
foreach($foo as $k=>$v)
{
$foo[$k][$i] = $k;
$i = (string)((int)$i%2 === 0 ? ((int)$i/2)+1 : (int)$i*3);
}
function sortCB($a,$b)
{
$i = array_keys($a);
$j = array_keys($b);
if (end($i) === end($j))
{
return 0;
}
return (end($i) > end($j) ? 1 : -1);
}
uasort($foo,'sortCB');
var_dump($foo);
但是由于你使用的是框架,你可能会很好地声明函数作为一个成员函数 private function sortCB(array $ a,array $ b)
,并使用它:
But since you're using a framework, you might do well declaring that function as a member function private function sortCB(array $a,array $b)
, and use it like so:
uasort($foo,array($this, 'sortCB'));
可能有更多的信息,说明如何在类上下文中使用这个回调函数
There might be some more info on how best to use this callback function in a class context here
完整示例+用法(测试和工作):
Full example + usage (tested and working):
class test
{
public $foo = null;
public function __construct()
{
$this->foo = array_fill_keys(array('foo','bar','q','Bond'),array());
$i = '256';
foreach($this->foo as $k=>$v)
{
$this->foo[$k][$i] = $k;
$i = (string)((int)$i%2 === 0 ? ((int)$i/2)+1 : (int)$i*3);
}
}
private function sortCB($a,$b)
{
$i = array_keys($a);
$j = array_keys($b);
if (end($i) === end($j))
{
return 0;
}
return (end($i) > end($j) ? 1 : -1);
}
public function sortFoo()
{
uasort($this->foo,array($this,'sortCB'));
print_r($this->foo);
return $this->foo;
}
}
$bar = new test();
$arr = $bar->sortFoo();
这篇关于排序关联数组codeigniter php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!