我有一个看起来像这样的数组
Array ( [0] => Array ( [make] => Alfa Romeo [id] => 2 )
[1] => Array ( [make] => Aston Martin [id] => 3 )
[2] => Array ( [make] => Audi [id] => 4 )
[3] => Array ( [make] => BMW [id] => 8 )
[4] => Array ( [make] => Caterham [id] => 9 )
)
我想将其垂直排序为2列
所以看起来像这样
Alfa Romeo BMW
Aston Martin Caterham
Audi
现在,当Yii使用checkBoxList()
函数
Alfa Romeo Aston Martin
Audi BMW
Caterham
现在我有这个要排序。但这仅适用于1维数组
function array_chunk_vertical($data, $columns = 2) {
$n = count($data) ;
$per_column = floor($n / $columns) ;
$rest = $n % $columns ;
// The map
$per_columns = array( ) ;
for ( $i = 0 ; $i < $columns ; $i++ ) {
$per_columns[$i] = $per_column + ($i < $rest ? 1 : 0) ;
}
$tabular = array( ) ;
foreach ( $per_columns as $rows ) {
for ( $i = 0 ; $i < $rows ; $i++ ) {
$tabular[$i][ ] = array_shift($data) ;
}
}
return $tabular ;
}
答案 0 :(得分:1)
您的现有函数无法阻止它在n维数组上使用。实际上,您在此处显示的功能gives exactly the desired output使用提供的输入。
<?php
function array_chunk_vertical($data, $columns = 2) {
$n = count($data) ;
$per_column = floor($n / $columns) ;
$rest = $n % $columns ;
// The map
$per_columns = array( ) ;
for ( $i = 0 ; $i < $columns ; $i++ ) {
$per_columns[$i] = $per_column + ($i < $rest ? 1 : 0) ;
}
$tabular = array( ) ;
foreach ( $per_columns as $rows ) {
for ( $i = 0 ; $i < $rows ; $i++ ) {
$tabular[$i][ ] = array_shift($data) ;
}
}
return $tabular ;
}
$cars = [
[ 'make' => 'Alfa Romeo', 'id' => 2 ],
[ 'make' => 'Aston Martin', 'id' => 3 ],
[ 'make' => 'Audi', 'id' => 4 ],
[ 'make' => 'BMW', 'id' => 8 ],
[ 'make' => 'Caterham', 'id' => 9 ],
];
echo '<table>';
foreach(array_chunk_vertical($cars) as $row) {
echo '<tr>';
foreach($row as $car) {
echo '<td><input type="checkbox" value="', $car['id'], '" />', $car['make'], '</td>';
}
echo '</tr>';
}
echo '</table>';
答案 1 :(得分:0)
在这种情况下,您应该将数据添加到新的一维数组中。尝试类似下面的内容
$a = array(0 => array( 'make' => 'Alfa Romeo', 'id' => 2 ),
1 => array( 'make' => 'Aston Martin', 'id' => 3 ),
2 => array( 'make' => 'Audi', 'id' => 4 ),
3 => array( 'make' => 'BMW', 'id' => 8 ),
4 => array( 'make' => 'Caterham', 'id' => 9 )
);
$b=array();
foreach ($a as $v)
{
$b[]=$v['make'];
}
sort($b);
print_r($b);
然后你可以使用你的工作函数传递新数组作为参数。
答案 2 :(得分:0)
试试这个,添加一些条件以显示在你的两栏
中<?php $sort=Array (
0 => Array ( 'make' => 'Alfa Romeo' ,'id' => 2 ),
1 => Array ( 'make' => 'Aston Martin' ,'id' => 3 ) ,
2 => Array ( 'make' => 'Audi' ,'id' => 4 ),
3 => Array ( 'make' => 'Caterham' ,'id' => 8 ),
4 => Array ( 'make' => 'BMW' , 'id' => 9 )
);
print_r($sort);
sort($sort); echo ' <br/>';
print_r($sort);
?>