Acubi
Acubi

Reputation: 2783

Parse hyphen-delimited strings and push prefixes into suffix-grouped subarrays

Array
(
    [0] => 46-sen1-Grid1-138
    [1] => 47-sen2-Grid1-138
    [2] => 50-sen5-Grid2-144
    [3] => 51-sen6-Grid2-144
)

How to make the above array as following?

Array
(
    [138] => Array
        (
            [0] => 46-sen1
            [1] => 47-sen2
        )
    [144] => Array
        (
            [0] => 50-sen5
            [1] => 51-sen6
        )
)

Upvotes: 0

Views: 60

Answers (4)

mickmackusa
mickmackusa

Reputation: 47874

Split each value by -Grid#- substrings, use the suffix as the grouping key and push the prefix as a new element in the group's subarray. Demo

$result = [];
foreach ($array as $v) {
    [1 => $k, 0 => $result[$k][]] = preg_split('/-Grid\d+-/', $v);
}
var_export($result);

Output:

array (
  138 => 
  array (
    0 => '46-sen1',
    1 => '47-sen2',
  ),
  144 => 
  array (
    0 => '50-sen5',
    1 => '51-sen6',
  ),
)

Upvotes: 0

Sumit Neema
Sumit Neema

Reputation: 480

You Can Use The following code and please do apply checks on array key and values i have just written a basic structure

  $a[0] =' 46-sen1-Grid1-138';
    $a[1] = '47-sen2-Grid1-138';
    $a[2] = '50-sen5-Grid2-144';
    $a[3] = '51-sen6-Grid2-144';

  $KeyArray=array();
   foreach($a as $row)
   {
    $check=explode('-',$row);
    print_r($check);

    $KeyArray[$check[3]][] = $check[0].'-'.$check[1];

   }

   print_r($KeyArray);

Upvotes: 0

Bjoern
Bjoern

Reputation: 16304

Loop through it, parse it and generate a new one.

Here's an easy example of how this can be done:

$arr = array("46-sen1-Grid1-138", 
    "47-sen2-Grid1-138", 
    "50-sen5-Grid2-144", 
    "51-sen6-Grid2-144");

foreach ($arr as $item) {
    $arr_n[substr($item,-3)][] = substr($item,0,7);
}

var_dump($arr_n);

Upvotes: 0

Sfynx
Sfynx

Reputation: 365

$from = array(
    '46-sen1-Grid1-138'
    '47-sen2-Grid1-138',
    '50-sen5-Grid2-144',
    '51-sen6-Grid2-144'
);

$to = array();

foreach($from as $value) {
    $elements = explode('-',$value);
    if (!isset($to[$elements[3]])) $to[$elements[3]] = array();
    $to[$elements[3]][] = $elements[0].'-'.$elements[1];
}

Upvotes: 1

Related Questions