php,操纵数组,组合数组,关联

时间:2010-08-18 19:38:58

标签: php arrays

我有一个类似

的数组
$array = Manufacturer => BMW
         Miles => 10000

我想用它来创建一个具有特定名称/值的新数组,如下所示:

$array = st_selval_0_0 => Manufacturer
         st_tmdata_0_0 => BMW

         st_selval_0_1 => Miles
         st_tmdata_0_1 => 10000

正如您所看到的,每个新名称=>值必须增加最后一位数字。

3 个答案:

答案 0 :(得分:3)

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

另请参阅手册中的foreach

答案 1 :(得分:1)

$newArray = array();
$i=0;

foreach($array as $k => $v)
{
  $newArray["st_selval_0_$i"] = $k;
  $newArray["st_tmdata_0_$i"] = $v;
  $i++;
}

答案 2 :(得分:1)

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

输出:

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