我有一个包含对象的属性$this->result
:
array(40) {
[0] => object(Model)#181 (7) {
["_id":protected] => string(2) "1"
["_img":protected] => string(95) "/1273720855.jpg"
}
[1] => object(Model)#224 (7) {
["_id":protected] => string(2) "2"
["_img":protected] => string(95) "/test.jpg"
}
[2] => object(Model)#182 (7) {
["_id":protected] => string(2) "3"
["_img":protected] => string(95) "/127377775.jpg"
}
[3] => object(Model)#224 (7) {
["_id":protected] => string(2) "4"
["_img":protected] => string(95) "/test.jpg"
}
[4] => object(Model)#182 (7) {
["_id":protected] => string(2) "5"
["_img":protected] => string(95) "/129586775.jpg"
}
...
所以,如果我做一个循环,我可以获得img
属性:
foreach($this->result as $val){
echo $val->getImg(); //'/1273720855.jpg'
}
我想要做的是对对象进行排序,使得/test.jpg
的属性为最后一个或最后回显它们,如:
array(40) {
[2] => object(Model)#182 (7) {
["_id":protected] => string(2) "3"
["_img":protected] => string(95) "/127377775.jpg"
}
[4] => object(Model)#182 (7) {
["_id":protected] => string(2) "5"
["_img":protected] => string(95) "/129586775.jpg"
}
[1] => object(Model)#224 (7) {
["_id":protected] => string(2) "2"
["_img":protected] => string(95) "/test.jpg"
}
[3] => object(Model)#224 (7) {
["_id":protected] => string(2) "4"
["_img":protected] => string(95) "/test.jpg"
}
....
我对任何解决方案感兴趣,即使我必须创建一个可以对其进行排序的新阵列等等
蚂蚁的想法?感谢答案 0 :(得分:4)
你所追求的是我们。
bool usort ( array &$array , callable $cmp_function )
编写运行排序的函数,并将此函数作为参数2传递。 然后,PHP将遍历数组并针对数组中的每个值运行该函数。
所以你应该有类似的东西:
<?php
function cmp($a, $b)
{
return strcmp($a->getImg(), $b->getImg());
}
usort($this->result, "cmp");
答案 1 :(得分:2)
我可以看到你已超过40 Images
并且它仍然可以增长等等。并且我不确定你从哪里获得它但是可以使用堆来存储你的图像并且它会自动排序。 。
$heap = new ImageStorage();
// Porpulate Storage form source
$images = array(1 => "/1273720855.jpg",2 => "/test.jpg",3 => "/127377775.jpg",4 => "/test.jpg",5 => "/129586775.jpg");
foreach ( $images as $id => $img ) {
$heap->insert(new Model($id, $img));
}
// Simple Output
echo "<pre>";
foreach ( $heap as $img ) {
echo $img->getImg(), PHP_EOL;
}
输出
/1273720855.jpg
/127377775.jpg
/129586775.jpg
/test.jpg
/test.jpg
使用的课程
// Image Sotrage Class
class ImageStorage extends SplHeap {
public function compare($a, $b) {
return strcmp($b->getImg(), $a->getImg());
}
}
// Emulation of your Model class
class Model {
protected $_id;
protected $_img;
function __construct($id, $img) {
$this->_id = $id;
$this->_img = $img;
}
public function getID() {
return $this->_id;
}
public function getImg() {
return $this->_img;
}
}