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

在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
    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
    )
    
    点赞 评论
  • dsvq5069
    dsvq5069 2016-10-31 23:06

    I'm not exactly sure what you want to do, but your output could be done by this:

      $max_val = 2;
      for($i=0; $i<$max_val; $i++)
      {
            $flr_arr = [];
            $flr_arr['key'] = 'fl_".$i."_sq';
            print_r($flr_arr);
      }
    
    点赞 评论
  • dongzouhe9734
    dongzouhe9734 2016-10-31 23:07

    You're declaring a string and concatenating it. You want to add elements to an array. You also can't create multiple arrays with the same name. What you can do, though is a 2D array:

    $flr_arr[] = array("key"=>"fl_$i_sq");
    

    Note the lack of quotes around array(). The "[]" syntax adds a new element to the end of the array. The output would be -

    array(array('key' => 'fl_0_sq'),array('key' => 'fl_1_sq'))
    
    点赞 评论

相关推荐