按值排序数组

时间:2014-08-15 08:42:14

标签: php arrays sorting

我有这个数组:

array(
 "tour_0" => 1446,
 "tour_1" => 1471,
 "date-from-1471" => "2014-08-07",
 "date-to-1471" => "2014-08-15",
 "tour_2" => 30,
 "date-from-30" => 2014-08-01,
 "date-to-30" => 2014-08-05,
 "tour_3" => 10
)

现在,我需要对它进行分类:

array(
 "0" => array("ID" => 1446),
 "1" => array("ID" => 1471, "from" => "2014-08-07", "to" => "2014-08-15"),
 "2" => array("ID" => 30, "from" => "2014-08-07", "to" => "2014-08-15"),
 "3" => array("ID" => 10),
)

我怎样才能完成这件事? 我尝试过各种各样的事情,但我似乎无法想出这个......

感谢并对标题感到抱歉,但我不知道如何描述它。

1 个答案:

答案 0 :(得分:1)

这个怎么样?

$ret = [];
foreach($inputArray as $key => $value) {
  if (preg_match('/^tour_([0-9]+)/', $key)) {
    $ret[$value] = ["ID" => $value];
  }

  if (preg_match('/date-from-([0-9]+)/', $key, $matches)) {
    $ret[$matches[1]]["from"] = $value;
  }

  if (preg_match('/date-to-([0-9]+)/', $key, $matches)) {
    $ret[$matches[1]]["to"] = $value;
  } 
}

print_r($ret);
/*
Array
(
    "1446" => Array ("ID" => 1446),
    "1471" => Array ("ID" => 1471, "from" => "2014-08-07", "to" => "2014-08-15"),
    "30"   => Array ("ID" => 30, "from" => "2014-08-01", "to" => "2014-08-05"),
    "10"   => Array ("ID" => 10)
)*/

足够接近? (这是非常繁琐的更改数组的键,考虑到它们是有序的(0,1,2,3,...),如果它们不是,也许你也可以保存顺序(在子阵列的另一项中)并且一旦形成这个数组就重新组合)