我有这个数组:
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),
)
我怎样才能完成这件事? 我已经尝试了各种各样的方法,但我似乎无法弄清楚这一点......
感谢并抱歉这个标题,但我只是不知道如何描述它。
这个怎么样?
$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,...),改变数组的键是相当简单的,如果它们不是,也许你也可以保存顺序(在子数组的另一项中) )并在该数组形成后再次重组)
无需在结果数组中写入关联的第一级键。当遇到 id 行时,立即访问其相关的“from”和“to”值。
代码:(演示)
$result = [];
foreach ($array as $k => $v) {
if (sscanf($k, 'tour_%d', $id)) {
$row = ['ID' => $id];
foreach (['from', 'to'] as $prefix) {
if (isset($array["date-$prefix-$v"])) {
$row[$prefix] = $array["date-$prefix-$v"];
}
}
$result[] = $row;
}
}