views:

85

answers:

1

i have this array:

Array
    (
      0 => "3_some val",
      1 => "1_some other val",
      2 => "0_val",        
      3 => "2_value",
      4 => "4_other value"
    )

considering the above array, is there a way to do from that an array like this?

Array
    (
      0 => "val",
      1 => "some other val",
      2 => "value",        
      3 => "some val",
      4 => "other value"
    )

actually to force the number that precedes that underscore(_) to be the key in the newly created array. thanks

+5  A: 

This should do it:

$arr1 = array (
  0 => "3_some val",
  1 => "1_some other val",
  2 => "0_val",        
  3 => "2_value",
  4 => "4_other value"
);

$result = array();

foreach($arr1 as $val) {
    list($key, $value) = explode('_', $val, 2);
    $result[$key] = $value;
}

// Sort by keys
ksort($result);

Doing print_r($result) will print out:

Array
(
    [0] => val
    [1] => some other val
    [2] => value
    [3] => some val
    [4] => other value
)
Tatu Ulmanen
what about 2 => "0_val", 3 => "2_value",
streetparade
Better use `explode('_', $val, 2)`.
Gumbo
@streetparade, what about them? As you can see, the result is just as OP intended. There will be no collisions as the values are inserted in a new array.
Tatu Ulmanen
@Gumbo, that's true, fixed.
Tatu Ulmanen