如何指定数组中应显示的顺序项目?
我得到了一个 3 级数组,有点像下面:
Array
(
[AK] => Array
(
[ACO] => Array
(
[FFS] => Array
(
[Medicaid] => -
[CHIP] => -
)
)
[ZCO] => Array
(
[FFS] => Array
(
[Medicaid] => -
[CHIP] => -
)
)
[Other] => Array
(
[FFS] => Array
(
[Medicaid] => -
[CHIP] => -
)
)
)
[AR] => Array
(
[Other] => Array
(
[Other] => Array
(
[Medicaid] => -
[CHIP] => -
)
)
[ACO] => Array
(
[FFS] => Array
(
[Medicaid] => -
[CHIP] => -
)
)
[ZCO] => Array
(
[FFS] => Array
(
[Medicaid] => -
[CHIP] => -
)
)
)
)
如何使它们按第二级命名元素对第一个元素列表进行排序[AK]
(我需要它们都[ACO], [ZCO], [Other]
)?
字典是没有顺序的数据结构。
但是 php 默认按照粘贴元素的顺序迭代项目。
因此,您可以按必要的顺序
简单地重新创建数组或者使用 php usort 方法编写自定义排序函数。
小例子:
function compare($a, $b)
{
$order = array('ACO', 'ZCO', 'Other');
$ai = array_search($a, $order);
$bi = array_search($b, $order);
return $ai<$bi ? -1 : $ai>$bi;
}
$a = array('ZCO'=>1, 'Other'=>1, 'ACO'=>1);
uksort($a, "compare");
print_r($a);
// CREATE THE TEST DATA
$arr = Array
( 'AK' => Array
( 'ACO' => Array( 'FFS' => Array( 'Medicaid' => '-', 'CHIP' => '-' ) )
, 'ZCO' => Array( 'FFS' => Array( 'Medicaid' => '-', 'CHIP' => '-' ) )
, 'Other' => Array( 'FFS' => Array( 'Medicaid' => '-', 'CHIP' => '-' ) )
)
, 'AR' => Array
( 'Other' => Array( 'FFS' => Array( 'Medicaid' => '-', 'CHIP' => '-' ) )
, 'ACO' => Array( 'FFS' => Array( 'Medicaid' => '-', 'CHIP' => '-' ) )
, 'ZCO' => Array( 'FFS' => Array( 'Medicaid' => '-', 'CHIP' => '-' ) )
)
)
;
// ACTIVATE THIS TO ANSWER THE QUESTION: DOES IT LOOK RIGHT?
// print_r($arr);
// GET THE ORDER FOR THE [AK] ARRAY
$pat = array_keys($arr['AK']);
// ITERATE OVER THE ARRAY TO PRODUCE THE ORDERED OUTPUT
$out = array();
foreach($arr as $key => $inner)
{
// SKIP THE SIGNAL ARRAY
if ($key == 'AK')
{
$out[$key] = $inner;
continue;
}
// REORDER THE OTHER ARRAYS
else
{
$temp = array();
foreach ($pat as $inner_key)
{
$temp[$inner_key] = $inner[$inner_key];
}
$out[$key] = $temp;
}
}
// SHOW THE WORK PRODUCT
print_r($out);