dpuwov1487 2014-04-30 17:47
浏览 737
已采纳

将关联数组转换为索引数组的方法

I have an associative array with indexed sub-arrays each containing associative arrays which contain content and an index. So like this (in 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")
                      )
);

I want to put all of those into an indexed array where their index is their "position" in the associative array. So final array should be:

Array ( [0] => Hail [1] => to [2] => the [3] => Victors [4] => Valiant [5] => Hail ) 

Currently, I'm merging all of the arrays inside the highest level array, then sorting it by each of those sub-array's positions, then creating an indexed array by pushing the content in order onto a new array. As so:

$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"]);
}

It seems like there must be a better way to do this! Can anyone think of one?

The data is coming from a poorly structured XML document which I can't change.

  • 写回答

2条回答 默认 最新

  • dtjo51649 2014-04-30 17:52
    关注
    $idxar=array();
    foreach ($assoc_arr as $subar)
      foreach ($subar as $item)
        $idxar[$item['position']+0]=$item['content'];
    

    will work, if your input data is flawless.

    Edit

    If you need the keys not only to be numerically correct, but also in the correct order, you must suffix this with ksort($idxar)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧