下面的数组需要按planning_no字段排序
Array ( [0] => stdClass Object ( [planning_no] => 100-3 [pieces] => 0 ) [1] => stdClass Object ( [planning_no] => 100 [pieces] => 0 ) [2] => stdClass Object ( [planning_no] => 100-2 [pieces] => 0 ) [3] => stdClass Object ( [planning_no] => 100 [pieces] => 148 ) [4] => stdClass Object ( [planning_no] => 102 [pieces] => 0 ) [5] => stdClass Object ( [planning_no] => 100-1 [pieces] => 0 ) )
我希望数组采用以下格式
Array ( [0] => stdClass Object ( [planning_no] => 100 [pieces] => 0 ) [1] => stdClass Object ( [planning_no] => 100 [pieces] => 148 ) [2] => stdClass Object ( [planning_no] => 100-1 [pieces] => 0 ) [3] => stdClass Object ( [planning_no] => 100-2 [pieces] => 0 ) [4] => stdClass Object ( [planning_no] => 100-3 [pieces] => 0 ) [5] => stdClass Object ( [planning_no] => 102 [pieces] => 0 ) )
答案 0 :(得分:1)
使用php array_multisort()函数。
工作代码:
<?php
$values = array();
$a = new stdClass();
$a->planning_no = '100-3';
$a->pieces = '0';
$values[] = $a;
$a = new stdClass();
$a->planning_no = '100';
$a->pieces = '0';
$values[] = $a;
$a = new stdClass();
$a->planning_no = '100-2';
$a->pieces = '0';
$values[] = $a;
$a = new stdClass();
$a->planning_no = '100';
$a->pieces = '148';
$values[] = $a;
$a = new stdClass();
$a->planning_no = '102';
$a->pieces = '0';
$values[] = $a;
$a = new stdClass();
$a->planning_no = '100-1';
$a->pieces = '0';
$values[] = $a;
$n = array();
if (! empty($values)) {
foreach ($values as $value) {
$planning_no = str_replace('-', '.', $value->planning_no);
$n[] = array('planning_no' => $planning_no, 'pieces' => $value->pieces);
}
}
array_multisort($n);
$final = array();
if (! empty($n)) {
foreach ($n as $elem) {
$planning_no = str_replace('.', '-', $elem['planning_no']);
$a = new stdClass();
$a->planning_no = $planning_no;
$a->pieces = $elem['pieces'];
$final[] = $a;
}
}
echo '<pre>';print_r($final);echo '</pre>';
?>
<强>输出:强>
Array
(
[0] => stdClass Object
(
[planning_no] => 100
[pieces] => 0
)
[1] => stdClass Object
(
[planning_no] => 100
[pieces] => 148
)
[2] => stdClass Object
(
[planning_no] => 100-1
[pieces] => 0
)
[3] => stdClass Object
(
[planning_no] => 100-2
[pieces] => 0
)
[4] => stdClass Object
(
[planning_no] => 100-3
[pieces] => 0
)
[5] => stdClass Object
(
[planning_no] => 102
[pieces] => 0
)
)