【发布时间】:2014-04-30 17:47:45
【问题描述】:
我有一个带有索引子数组的关联数组,每个子数组都包含包含内容和索引的关联数组。就像这样(在 PHP 中):
$assoc_arr =
array("second" => array(
array("position" => 4,
"content" => "Valiant"),
array("position" => 5,
"content" => "Hail")
),
"first" => array(
array("position" => 0,
"content" => "Hail"),
array("position" => 3,
"content" => "Victors"),
array("position" => 2,
"content" => "the"),
array("position" => 1,
"content" => "to")
)
);
我想将所有这些放入索引数组中,其中它们的索引是它们在关联数组中的“位置”。所以最终的数组应该是:
Array ( [0] => Hail [1] => to [2] => the [3] => Victors [4] => Valiant [5] => Hail )
目前,我正在合并最高级别数组中的所有数组,然后按每个子数组的位置对其进行排序,然后通过将内容按顺序推送到新数组中来创建索引数组。因此:
$pos_arr = array_merge($assoc_arr["second"], $assoc_arr["first"]);
usort($pos_arr, function($a, $b) {
return $a["position"] >= $b["position"] ? 1 : -1;
});
$indexed_arr = array();
foreach ($pos_arr as $elem) {
array_push($indexed_arr, $elem["content"]);
}
似乎必须有更好的方法来做到这一点!谁能想到一个?
数据来自结构不佳的 XML 文档,我无法更改。
【问题讨论】: