为什么先前的数组值在新循环中被转移?

时间:2017-12-07 09:59:08

标签: php arrays

我有以下代码以重力形式填充复选框字段。我有一个field_ids我正在使用foreach循环循环的数组。 $arr = array(5, 6, 7, 8, 9);然后,我有一个带有查询的第二个foreach循环,该查询从数据库中提取数据。

然而,代码正在运行,每个后续的field_id都会显示该field_id和之前的结果。例如,field_id=6显示field_id=5field_id=6的复选框字段列表。 field_id= 7正在显示field_id=5field_id=6field_id=7等的复选框字段列表。

function populate_checkboxes( $form ){

    foreach( $form['fields'] as &$field )  {
        $arr = array(5, 6, 7, 8, 9);

        foreach($arr as $field_id){
          global $wpdb;
          $query = $wpdb->get_results( "SELECT sefer FROM bulk_import where field_id_select_items = {$field_id}" );
          foreach($query as $sefer){

            if ( $field->id != $field_id ) {continue;}
            $choices[] = array( 'text' => 'Select All', 'value' => 'Select_all' ); 
            $inputs[] = array( 'label' => 'Select All', 'id' => '1'); 
            //get all $sefer values
            $posts = get_posts(array(
            'post_type'=> array('learning_item'),   'suppress_filters' => 0, 'posts_per_page' => -1, 'order' => 'asc', 
            'meta_query' => array(  
                array( 'key' => 'taken',   'value' => '0'),
                array('key' => 'torah', 'value' => $sefer -> sefer)
            ),
            ));

            $input_id = 2;
            foreach( $posts as $post ) {
                //skipping index that are multiples of 10 (multiples of 10 create problems as the input IDs)
                if ( $input_id % 10 == 0 ) {$input_id++;}
                $choices[] = array( 'text' => $post->post_title, 'value' => $post->post_title );
                $inputs[] = array( 'label' => $post->post_title, 'id' => "{$field_id}.{$input_id}" );

                $input_id++;
            }

            $field->choices = $choices; 
            $field->inputs = $inputs; 

          }
            //reset query here? 
             wp_reset_query();
        }

    }
    return $form;}

我是否需要将变量设置为在数组中的某处清空?为什么要传输数据?如何仅显示与特定field_id相关联的值?

1 个答案:

答案 0 :(得分:1)

在每个循环开始时,您需要重置构建值的数组。它可能像......

find

除非你重置它们,否则它们仍然具有上一循环中的值。