我有一个格式为“Year-Month_ID”的字符串数组。我想把'_'中的每个项目分成两部分。然后,对于具有相同前缀(年和月)的项目,请在前缀(“Year-Month_ID_ID ...”)之后使用“_”加入ID。例如,如果我有数据:
array(
'2010-December_9',
'2010-December_19',
'2011-June_4',
'2011-September_38',
'2011-November_29',
'2011-November_9'
)
我希望结果是:
array(
'2010-December_9_19',
'2011-June_4',
'2011-September_38',
'2011-November_29_9'
)
我该怎么做?
答案 0 :(得分:2)
$arr = array();
foreach ($dates as $val)
{
$tmp = explode("_", $val);
if ( ! isset($arr[$tmp[0]]))
{
$arr[$tmp[0]] = array();
}
$arr[$tmp[0]][] = $tmp[1];
}
$final = array();
foreach ($arr as $key=>$val)
{
$final[] = $key."_".implode("_", $val);
}
答案 1 :(得分:1)
这可能会有所帮助:
$arr = Array('2010-December_9', '2010-December_19', '2011-June_4', '2011-September_38', '2011-November_29', '2011-November_9'); // input array
$arrTemp = $arrOutput = Array();
foreach ($arr as $val) {
if (preg_match('/([0-9]{4})-([a-z]+)_([0-9]{1,2})/i', $val, $arrMatches)) {
$arrTemp[$arrMatches[1] . '-' . $arrMatches[2]][] = $arrMatches[3];
}
}
foreach ($arrTemp as $key => $day) {
$arrOutput[] = $key . '_' . implode('_', $day);
}
print_r($arrOutput);
答案 2 :(得分:0)
explode('_',$str)
http://php.net/manual/en/function.explode.php
我将记下一个简单的逻辑..用代码实现它。
create array2
for loop till all elem in array1
loop2 for array1
if index1!=index2 && explode('_',array[index1])[0]== explode('_',array[index2])[0]
array2.push( explode('_',array[index1])[0]).explode('_',array[index1])[1]).'_'.explode('_',array[index2])[1])
array1.pop(index1)
array1.pop(index2)
loop end
loop end
for loop till all rem elem in array1
array2.push(array1[index])
loop end