我在这里有一个数组:
$array = array(
array('t'=>'t1','v'=>'001'),
array('t'=>'t2','v'=>'002'),
array('t'=>'t3','v'=>'003'),
array('t'=>'t1','v'=>'004'),
array('t'=>'t4','v'=>'005'),
array('t'=>'t2','v'=>'006'),
array('t'=>'t5','v'=>'007'),
array('t'=>'t3','v'=>'008'),
);
我想要的最终数组是:
array(
't1' => array('v'=>array(001,004)),
't2' => array('v'=>002),
't3' => array('v'=>array(003,008)),
't4' => array('v'=>005),
't5' => array('v'=>006),
't6' => array('v'=>007)
)
有什么方法可以使用php数组操作函数实现最终数组?我不想使用任何循环(for或foreach)。尝试使用usort()但没有在哪里
这是我调用用户定义函数的usort代码:
public function sort($a,$b)
{
$const = array();
$temp1 = array();
$temp2 = array();
//echo $a['t'].":".$a['v'] . " - " . $b['t'].":".$b['v']. "<br/>";
if($a['t'] == $b['t']){
$temp1[$a['t']] = array($a['v'],$b['v']);
//$const = $temp1;
}else{
if(!array_key_exists($a['t'],$temp1) && !array_key_exists($b['t'],$temp1)){
$temp2[$a['t']] = array($a['v']);
$temp2[$b['t']] = array($b['v']);
}
}
$result = array_merge($temp1, $temp2);
print_r($result);
}
答案 0 :(得分:2)
$array = array(
array('t'=>'t1','v'=>'001'),
array('t'=>'t2','v'=>'002'),
array('t'=>'t3','v'=>'003'),
array('t'=>'t1','v'=>'004'),
array('t'=>'t4','v'=>'005'),
array('t'=>'t2','v'=>'006'),
array('t'=>'t5','v'=>'007'),
array('t'=>'t3','v'=>'008'),
);
$res = array();
foreach($array as $val){
$res[$val['t']]['v'][] = $val['v'];
}
echo "<pre>";
print_r($res);
输出:
Array
(
[t1] => Array
(
[v] => Array
(
[0] => 001
[1] => 004
)
)
[t2] => Array
(
[v] => Array
(
[0] => 002
[1] => 006
)
)
[t3] => Array
(
[v] => Array
(
[0] => 003
[1] => 008
)
)
[t4] => Array
(
[v] => Array
(
[0] => 005
)
)
[t5] => Array
(
[v] => Array
(
[0] => 007
)
)
)
答案 1 :(得分:0)
尝试:
$input = array( /* your data */ );
$output = array();
foreach ( $input as $value ) {
$t = $value['t'];
$v = $value['v'];
if ( !isset($output[$t]) ) {
$output[$t] = array('v' => $v);
} else if ( is_array($output[$t]['v']) ) {
$output[$t]['v'][] = $v;
} else {
$output[$t]['v'] = array($output[$t]['v'], $v);
}
}
答案 2 :(得分:0)
<?php
$array = array(
array('t'=>'t1','v'=>'001'),
array('t'=>'t2','v'=>'002'),
array('t'=>'t3','v'=>'003'),
array('t'=>'t1','v'=>'004'),
array('t'=>'t4','v'=>'005'),
array('t'=>'t2','v'=>'006'),
array('t'=>'t5','v'=>'007'),
array('t'=>'t3','v'=>'008'),
);
foreach ($array as $key => $row) {
$t[$key] = $row['t'];
$v[$key] = $row['v'];
}
array_multisort($v, SORT_ASC, $array);
$reqArray = array();
foreach($array as $value)
{
$reqArray[$value['t']]['v'][] = $value['v'];
}
print_r($reqArray);
?>