douren8379 2016-10-31 22:59
浏览 184
已采纳

在php中使用for循环构建关联数组

I am trying to create an associative array using php. My desired output is

Array
(
     [key] => fl_0_sq
),
Array
(
     [key] => fl_1_sq
)

The code is

  $max_val = 2;  
  for($i=0; $i<$max_val; $i++)
  {
        $flr_arr .= "array('key' => 'fl_".$i."_sq'),";      
  }
  print_r($flr_arr);

Output is

array('key' => 'fl_0_sq'),array('key' => 'fl_1_sq'),

Now the issue is that it has become a string instead of an array. Is it at all possible to create a array structure like the desired output. Any help is highly appreciated.

  • 写回答

3条回答 默认 最新

  • douke3335 2016-10-31 23:06
    关注

    You could do this:

    <?php
    
    $flr_arr = [];
    
    $max_val = 2;
    for ($i = 0; $i < $max_val; $i++) {
      $flr_arr[][key] = 'fl_' . $i . '_sq';
    }
    
    $output = "<pre>";
    
    foreach ($flr_arr as $i => $flr_arr_item) {
      $output .= print_r($flr_arr_item, true);
      if($i < count($flr_arr)-1){
        $output = substr($output, 0, -1) . ",
    ";
      }
    }
    $output .= "</pre>";
    
    echo $output;
    

    The output:

    Array
    (
        [key] => fl_0_sq
    ),
    Array
    (
        [key] => fl_1_sq
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示