0

I have nested loop while and I'd like to create multidimensional array with some datas from these loops Output should be look like:

'productId'=>1 'productImg'=>some_url 'productContent'=> subarray( 'question1'=>value1 'answer1'=>value1, 'question2'=value2, 'question2'=>value2 ) 

My code with nested while loops

 if (have_rows('dodaj_pytania_do_produktu')): while (have_rows('dodaj_pytania_do_produktu')) : the_row(); $counter = 1; $productID = get_sub_field('nazwa_produktu_faq'); $productImage = get_sub_field('dodaj_zdjecie'); $productsData[] = array( 'productId' => $productID, 'productImg' => $productImage, ); $product = wc_get_product($productID); $productName = $product->get_title(); // Loop over sub repeater rows. if (have_rows('dodaj_pytanie_i_odpowiedz')): while (have_rows('dodaj_pytanie_i_odpowiedz')) : the_row(); $question = get_sub_field('dodaj_pytanie'); $answer = strip_tags(get_sub_field('dodaj_odpowiedz')); $productsData[] = array( 'productDesc'=> array( 'question' => $question, 'answer' => $answer ) ); endwhile; endif; endwhile; else : echo "brak faq"; endif; ?> 

Now my output create wrong subarray not creating a subarray

    1 Answer 1

    0

    There is no hurry to create the array, wait till you have everything, so create the new array at the end of the outer loop, and build a temp array for the productContent array, put it all together at then end

    if (have_rows('dodaj_pytania_do_produktu')): while (have_rows('dodaj_pytania_do_produktu')) : the_row(); $productID = get_sub_field('nazwa_produktu_faq'); $productImage = get_sub_field('dodaj_zdjecie'); $product = wc_get_product($productID); $productName = $product->get_title(); // Loop over sub repeater rows. if (have_rows('dodaj_pytanie_i_odpowiedz')): $x = 1; // counter $pc = []; while (have_rows('dodaj_pytanie_i_odpowiedz')) : the_row(); $question = get_sub_field('dodaj_pytanie'); $answer = strip_tags(get_sub_field('dodaj_odpowiedz')); // build the inner loop content here $pc[] = ["question$x" => $question, "answer$x" => $answer ]; $x++; endwhile; // put it all together here $productsData[] = [ 'productId' => $productID, 'productImg' => $productImage, 'productContent = $pc ]; endif; endwhile; else : echo "brak faq"; endif; 
    2
    • Perfect solution. Thank you very much :)
      – mm42
      CommentedFeb 9, 2022 at 8:23
    • Now best to go through this with nested foreach? I would like each product to display its content separately
      – mm42
      CommentedFeb 9, 2022 at 9:49

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.