Balaji Kandasamy
Balaji Kandasamy

Reputation: 4506

Spliting an array value and concatinating the array value in php

I have an array of strings of the format "Year-Month_ID". I'd like to split each item in two at the '_'. Then, for the items that have the same prefix (year & month), join the IDs with '_' after the prefix ("Year-Month_ID_ID..."). For example, if I have the data:

array(
    '2010-December_9',
    '2010-December_19',
    '2011-June_4',
    '2011-September_38',
    '2011-November_29',
    '2011-November_9'
)

I want the result to be:

array(
    '2010-December_9_19',
    '2011-June_4',
    '2011-September_38',
    '2011-November_29_9'
)

How can I do this?

Upvotes: 0

Views: 76

Answers (3)

Abhay
Abhay

Reputation: 6645

This might help:

$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);

Upvotes: 1

Gaurav Shah
Gaurav Shah

Reputation: 5279

explode('_',$str)

http://php.net/manual/en/function.explode.php

I will put down a simple logic .. implement it with code.

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

Upvotes: 0

ajreal
ajreal

Reputation: 47321

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

Upvotes: 2

Related Questions