我在排序该数组时遇到问题,我尝试了几种不同的方法,但似乎没有任何工作。 我想通过“vieworder”订购。 要打印它,我使用了array_values()函数 这是数组:
Array
(
[0] => Array
(
[0] => stdClass Object
(
[name] => 1.png
[size] => 673478
[url] => files/1.png
[thumbnailUrl] => files/thumbnail/1.png
[deleteUrl] => uploads/index.php?file=1.png&_method=DELETE
[deleteType] => POST
[id] => 17
[type] => image/png
[title] => test
[vieworder] => 1
)
[1] => stdClass Object
(
[name] => 10.png
[size] => 151629
[url] => files/10.png
[thumbnailUrl] => files/thumbnail/10.png
[deleteUrl] => uploads/index.php?file=10.png&_method=DELETE
[deleteType] => POST
[id] => 16
[type] => image/png
[title] => test10
[vieworder] => 10
)
[2] => stdClass Object
(
[name] => 11.png
[size] => 682790
[url] => files/11.png
[thumbnailUrl] => files/thumbnail/11.png
[deleteUrl] => uploads/index.php?file=11.png&_method=DELETE
[deleteType] => POST
[id] => 18
[type] => image/png
[title] => test
[vieworder] => 5
)
[3] => stdClass Object
(
[name] => 2.png
[size] => 118038
[url] => files/2.png
[thumbnailUrl] => files/thumbnail/2.png
[deleteUrl] => uploads/index.php?file=2.png&_method=DELETE
[deleteType] => POST
[id] => 15
[type] => image/png
[title] => test2
[vieworder] => 2
)
[4] => stdClass Object
(
[name] => 5.png
[size] => 496543
[url] => files/5.png
[thumbnailUrl] => files/thumbnail/5.png
[deleteUrl] => uploads/index.php?file=5.png&_method=DELETE
[deleteType] => POST
[id] => 14
[type] => image/png
[title] => test2
[vieworder] => 2
)
)
)
谢谢!
答案 0 :(得分:0)
假设您的数据结构如下:
$std_one = new stdClass();
$std_one->id = 3;
$std_one->name = 123;
$std_one->vieworder = 13;
$std_two = new stdClass();
$std_two->id = 1;
$std_two->name = 4;
$std_two->vieworder = 1;
$std_three = new stdClass();
$std_three->id = 1;
$std_three->name = 4;
$std_three->vieworder = 2;
$std_four = new stdClass();
$std_four->id = 1;
$std_four->name = 4;
$std_four->vieworder = 3;
// Data array which needs to be sorted according to vieworder property.
$data[0][] = $std_one;
$data[0][] = $std_two;
$data[0][] = $std_three;
$data[0][] = $std_four;
// Passing $data[0] variable in to our callback function sortStdClass
usort($data[0],'sortStdClass');
// Finally sortStdClass callback function
function sortStdClass($a, $b){
return $a->vieworder > $b->vieworder; // Sort in ASC order
}
// Print $data;
echo '<pre>'.print_r($data,1).'</pre>';
// Prints:
Array
(
[0] => Array
(
[0] => stdClass Object
(
[id] => 1
[name] => 4
[vieworder] => 1
)
[1] => stdClass Object
(
[id] => 1
[name] => 4
[vieworder] => 2
)
[2] => stdClass Object
(
[id] => 1
[name] => 4
[vieworder] => 3
)
[3] => stdClass Object
(
[id] => 1
[name] => 4
[vieworder] => 10
)
)
)
答案 1 :(得分:0)
更新: 我终于明白了: 因为对usort函数的调用来自一个类,所以usort方法应该是private static,而调用应该包含它。
usort($content[0], array($this, "sortStdClass"));
private static function sortStdClass($a, $b){
return $a->vieworder > $b->vieworder; // Sort in ASC order
}