tags:

views:

34

answers:

3

I have an array like

$array = Manufacturer => BMW
         Miles => 10000

and I would like to use this to create a new array with a specific name/value like this :

$array = st_selval_0_0 => Manufacturer
         st_tmdata_0_0 => BMW

         st_selval_0_1 => Miles
         st_tmdata_0_1 => 10000

As you can see the last digit must increase on each new name=>value.

+3  A: 
$result = array();
$i = 0;
foreach($array as $key => $val) {
  $result['st_selval_0_'.$i] = $key;
  $result['st_tmdata_0_'.$i] = $val;
  $i++;
}

See also foreach in the manual.

Emil Vikström
HAHA good answer! but your opening curly brace isn't on it's own line ;)
Byron Whitlock
No, because this is my coding style. Not everyone writes curly braces on their own line. Check the PHP documentation I linked to and you'll see that even the docs use "my" style...
Emil Vikström
I was joking, lighten up. ;)
Byron Whitlock
+1  A: 
$newArray = array();
$i=0;

foreach($array as $k => $v)
{
  $newArray["st_selval_0_$i"] = $k;
  $newArray["st_tmdata_0_$i"] = $v;
  $i++;
}
Byron Whitlock
opening curly brace is on it's own line! :D
Byron Whitlock
+1  A: 
$input = array('Manufacturer' => 'BMW', 'Miles' => 10000);
$output = array();

$i = 0;
foreach ($input as $key => $value) {
    $output['st_selval_0_' . $i] = $key;
    $output['st_tmdata_0_' . $i] = $value;
    $i++;
}

print_r($output);

Output:

Array
(
    [st_selval_0_0] => Manufacturer
    [st_tmdata_0_0] => BMW
    [st_selval_0_1] => Miles
    [st_tmdata_0_1] => 10000
)
Edward Mazur