Search code examples
phploopsforeacharray-key

reset key after count reached


So I am trying to grab just 4 keys at a time out of an array and then reset the key count back to 0 after the 4th one is reached (actually key #3, because the array starts with 0). Here's an example:

0 - USA Mix #1
1 - 24mg
2 - 252
3 - value
4 - USA Mix #1
5 - 24mg
6 - 252
7 - value

I have tried using unset($key['0']), unset($ket['1']), etc and that hasn't worked. I tried using array_shift and that doesn't seem to work. I'd like to reset the key pattern after 4 counts. The reason is, that on the 4th key looped, it is then supposed to do an insert grabbing the "block" (block contains 4 keys) - something like this:

foreach($temp_atts as $key=>$val){


            if($key == 0){
                $attribute_name = $val;
            }
            if($key == 1){
                $attribute_option = $val;
            }

          if($i <= 4){
               $sql_C = "SELECT * FROM attributes WHERE attribute_name = '{$attribute_name}' AND attribute_option = '{$attribute_option}' AND hc_cat = '{$_GET['cat_id']}' AND hc_s_cat = '{$_GET['sub_cat']}' AND hc_prod_id = '{$_GET['prod_id']}'";
               echo $sql_C . '<br>';


            $i = 0;
        }


        $i++;
    }

I'm having some difficulties getting it to reset the keys after the 4th count. Could someone offer a pointer as to what I am doing wrong or what I am missing? Thanks


Solution

  • This is not exactly a direct answer to your question, but a suggestion on how to better accomplish what (I think) you're trying to do.

    Consider using array_chunk():

    // Your current array. Values in [4] and [5] changed slightly for clarity
    $arr = array('USA Mix #1','24mg','252','value','USA Mix #2','240mg','252','value');
    
    $chunks = array_chunk($arr, 4);
    
    foreach ($chunks as $chunk) {
        $sql_C = "
        SELECT * FROM attributes
        WHERE attribute_name = '{$chunk[0]}' 
            AND attribute_option = '{$chunk[1]}'
        ";
        echo $sql_C . '<br>';
    }
    

    Output:

    SELECT * FROM attributes
    WHERE attribute_name = 'USA Mix #1' 
        AND attribute_option = '24mg'
    
    
    SELECT * FROM attributes
    WHERE attribute_name = 'USA Mix #2' 
        AND attribute_option = '240mg'
    

    Hopefully I am understanding your problem correctly, and this is helpful.

    *Note that I left off a large part of your query because I cannot endorse doing such as thing as putting $_GET values directly into a query. @Amal Murali's comment should help to clarify why.