Search code examples
phpforeachcontrolsassociative-arrayoperation

What is the method to execute PHP array one by one after insert into db for all arrays?


$countsara= array(array("a"=>"hello","b"=>"how","c"=>"are","d"=>"you","e"=>"david"),                    array("a"=>"hello","b"=>"how","c"=>"are","d"=>"you","e"=>"kaser"),array("a"=>"hello","b"=>"how","c"=>"are","d"=>"you","e"=>"albert"),array("a"=>"hello","b"=>"how","c"=>"are","d"=>"you","e"=>"stephen"));

    foreach ($countsara as $tommykey=>$tommyval) {
     foreach ($tommyval as $tommyvalkey=>$tommyvalval) {
      echo $tommyvalkey.' - '.$tommyvalval;
      echo '<br>';
      echo 'test';
      }
     }

For example, there are 100 arrays. I want to get the first array values and insert into db, then 2nd and then until 100th array values.

I can able to insert the value into db but the issue is, if there are 100 arrays. The foreach is executing for 100 times. So the insert is happening for 100 times for a same id on a same record row. Which is a re-insert not a duplicate.

If there are totally 100 arrays in $tommyval. As usual, the test is being executed for 10 times. I am going to do an operation in the place of echo test; So I don't want to repeat the same operation 100 times.

How to avoid this in PHP foreach array repetition at the same time I want all the array to be executed?


Solution

  • $countsara= array(array("a"=>"hello","b"=>"how","c"=>"are","d"=>"you","e"=>"david"),                    array("a"=>"hello","b"=>"how","c"=>"are","d"=>"you","e"=>"kaser"),array("a"=>"hello","b"=>"how","c"=>"are","d"=>"you","e"=>"albert"),array("a"=>"hello","b"=>"how","c"=>"are","d"=>"you","e"=>"stephen"));
    
        foreach ($countsara as $tommykey=>$tommyval) {
         foreach ($tommyval as $tommyvalkey=>$tommyvalval) {
          echo $tommyvalkey.' - '.$tommyvalval;
          echo '<br>';
          }
          echo 'test';
         }
    

    The change that I made was placed the echo 'test'; after the completion of second foreach. I got what I wanted. I executed only once and so as the insertion into db also happens only once.