PHP如何从数组创建新数组

时间:2014-04-28 16:13:59

标签: php arrays

我有一个包含Google字体(+600)的数组:

$google_fonts = array(
"ABeeZee" => "ABeeZee",
"Abel" => "Abel"
//......)

我需要这个新结构:

$google_fonts = array(
array('label' => 'ABeeZee','value' => 'ABeeZee'),
array('label' => 'Abel','value' => 'Abel')
//......)

我有这段代码,但它无效:

foreach( $google_fonts as $font ) {
  $google_fonts_array = array(
      'value' => $font,
      'label' => $font,
      'src' => ''
  );    
}
return $google_fonts_array;

此处应使用此数组(它是使用选择框的类型):

'choices' => array( //this is one old option
                array(
                    'value' => 'Open Sans',
                    'label' => 'Open Sans',
                    'src' => ''
                ), //and here is how I would retrieve the new array
                $google_fonts_array //or even using it instead of the previous level array, it's not working.
            )

为什么不起作用?

1 个答案:

答案 0 :(得分:0)

每次都要覆盖数组,而是执行此操作。 (注意[]

foreach( $google_fonts as $font ) {
  $google_fonts_array[] = array(
      'value' => $font,
      'label' => $font,
      'src' => ''
  );    
}
return $google_fonts_array;