如何将数组转换为不同的格式?

时间:2011-05-26 12:33:21

标签: php

您好 我想转换此数组,其中id为键和名称值对

Array(
    [4882] => treatment
    [4876] => Advance
    [4854] => Applied Clinical
)

Array(
    [0] => Array([id] => 4882, [name] => treatment)
    [1] => Array([id] => 4876, [name] => Advance)
    [2] => Array([id] => 4854, [name] => Applied Clinical)
)

3 个答案:

答案 0 :(得分:3)

foreach ($original_array as $key=>$value){
    $new_arrays[] = array('id'=>$key,'name'=>$value);
}

print_r($new_arrays);

答案 1 :(得分:2)

你可以这样做:

$output_arr = array();
foreach($input_arr as $key => $value)
  $output_arr[] = array('id' => $key, 'name' => $value);

然后你可以使用$ output_arr作为转换数组或将其内容分配给$ input_arr:

$input_arr = &$output_arr;

答案 2 :(得分:2)

$input是您的第一个数组,$output将保存结果数组

$output = array();
foreach ($input as $id => $name)
{
  $output[] = array('id'=>$id, 'name'=>$name);
}