Ali Zia
Ali Zia

Reputation: 3875

Conversion of an array from one form to another

I have an array.

Array
    (
        [0] => 1_4
        [1] => 1_1
        [2] => 1_2
        [3] => 2_3
        [4] => 2_5
    )

I want to convert it to

Array
    (
    [1] => Array (4,1,2)
    [2] => Array (3,5)
    )

Can any1 help me in this? The new keys (1 and 2) are the distinct values from 1st part of array before _.

Upvotes: 0

Views: 31

Answers (3)

clearshot66
clearshot66

Reputation: 2302

Quick and dirty...

foreach($array as $value){      // Loop your current array
  $arr = substr($value,0);              // Get the character before _, 1 or 2
  $val = substr($value,2);               // Get character after _, 1,2,3,4 or 5
  if($arr == 1){                // if 1_, put into first new array
     $newArray[0][] = $val; 
  }else{ 
     $newArray[1][] = $val;       // Put into second array else
  }
}
print_r($newArray);

Upvotes: 1

MTCoster
MTCoster

Reputation: 6145

Maybe try something like this?

foreach ($array as $element( {
  $kv_pair = explode("_", $element, 2);

  if (array_key_exists($kv_pair[0])) {
    array_push($new_array[$kv_pair[0]], $kv_pair[1]);
  } else {
    $new_array[$kv_pair[0]] = [$kv_pair[1]];
  }
}

Upvotes: 0

MCMXCII
MCMXCII

Reputation: 1026

If the underscore will always be the unique split you could explode on underscore and append results to a new array.

$before = ['1_4','1_1','1_2','2_3','2_5'];

$after = [];
foreach ($before as $entry) {
    $index = explode('_',$entry);
    $after[$index[0]][] = $index[1]; 
}

return $after;

Upvotes: 1

Related Questions