--- AIM ---
我有一个像这样的数组
$codes = array(
array('type'=>1,'id'=>'qcdv'),
array('type'=>2,'id'=>'thcd'),
array('type'=>2,'id'=>'ngjd'),
array('type'=>1,'id'=>'mhkx'),
array('type'=>3,'id'=>'tnfr') /* many more elements*/
);
并且所需的输出是
Array(
[0] => Array ()
[1] => Array (
[0] => qcdv
[1] => mhkx )
[2] => Array(
[0] => thcd
[1] => ngjd
)
[3] => Array (
[0] => tnfr
)
)
按类型键区分。
- 我现在试过什么 -
$codes = array(
array('type'=>1,'id'=>'qcdv'),
array('type'=>2,'id'=>'thcd'),
array('type'=>2,'id'=>'ngjd'),
array('type'=>1,'id'=>'mhkx'),
array('type'=>3,'id'=>'tnfr')
);
$by_type=array(array(),array(),array(),array()); /* unable to digest this line */
foreach($codes as $code) {
array_push($by_type[$code['type']],$code['id']);
}
print_r($by_type);
它提供了正确的输出,但类型键范围是不固定所以我无法使用
$by_type=array(array(),array(),array(),array());
还有其他有效方法吗?
答案 0 :(得分:3)
<?php
$codes = array(
array('type'=>1,'id'=>'qcdv'),
array('type'=>2,'id'=>'thcd'),
array('type'=>2,'id'=>'ngjd'),
array('type'=>1,'id'=>'mhkx'),
array('type'=>3,'id'=>'tnfr')
);
$array = array();
foreach( $codes as $v) {
$array[$v['type']][] = $v['id'];
}
print_r($array);
答案 1 :(得分:2)
这段代码可以解决问题:
$output = array();
foreach ($codes as $idx1 => $array2)
{
$k = $array2['type'];
$v = $array2['id'];
if (!isset($output[$k])) $output[$k] = array();
$output[$k][] = $v;
}
答案 2 :(得分:1)
<?php
$codes = array(
array('type'=>1,'id'=>'qcdv'),
array('type'=>2,'id'=>'thcd'),
array('type'=>2,'id'=>'ngjd'),
array('type'=>1,'id'=>'mhkx'),
array('type'=>3,'id'=>'tnfr') /* many more elements*/
);
$result = array();
foreach($codes as $code)
{
$result[$code['type']][] = $code['id'];
}
print_r($result);