Search code examples
phpforeachsequential

PHP sequential foreach


Guys i've got an array thats like this:

  array(3) {
    [2]=>
    array(1) {
      ["name"]=>
      array(2) {
        [0]=>
        string(13) "row1"
        [1]=>
        string(13) "row3"
      }
    }
    [5]=>
    array(1) {
      ["name"]=>
      array(2) {
        [0]=>
        string(15) "row1"
        [1]=>
        string(15) "row3"
      }
    }
    [3]=>
    array(1) {
      ["name"]=>
      array(2) {
        [0]=>
        string(13) "row1"
        [1]=>
        string(13) "row3"
      }
    }

What i want to achieve is make foreach loop the 0 elements (row1) and then loop through 1 (row3) and go on like this. Is there a way to do that?


Solution

  • You could try to rebuild the array:

    $rows = array();
    foreach($array as $subarray) 
      foreach($subarray as $key => $value)  
        $rows[$key][] = $value;
    

    At this point al the same subelements from the array are together in a new array, and now you can easy loop over a subelement:

      foreach($rows as $key => $value)  
        echo 'processing row: ' . $key ' with value ' . $value;