我有一个带有索引子数组的关联数组,每个子数组包含包含内容和索引的关联数组。就这样(在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")
)
);
我想将所有这些放入索引数组,其索引是" position"在关联数组中。所以最终的数组应该是:
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文档,我无法改变。
答案 0 :(得分:1)
$idxar=array();
foreach ($assoc_arr as $subar)
foreach ($subar as $item)
$idxar[$item['position']+0]=$item['content'];
如果您的输入数据完美无缺,将起作用。
修改强>
如果您需要的密钥不仅在数字上正确,而且顺序正确,则必须使用ksort($idxar)
答案 1 :(得分:1)
这是另一种解决方案:
<?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")
)
);
$order = array('first','second'); // this helps you create your own sort. E.g. position1, position2, etc
$arr = array();
foreach($order as $ord) {
if(isset($assoc_arr[$ord])) {
$arr = array_merge($arr, $assoc_arr[$ord]);
}
}
$finalArray = array();
foreach($arr as $a) {
$finalArray[$a['position']] = $a['content'];
}
ksort($finalArray);
print_r($finalArray);
和适合你的小提琴here