Andrew Chen
Andrew Chen

Reputation: 39

Separate array into multidimensional array based on condition

I have an array from a csv with data that I need to parse. The data is as follows:

Array
1. PO|115207534
2. OD|115207534
3. PO|115207535
4. OD|115207535
5. OD|115207536

I need to separate it into subarrays, with the first entry of each being the PO lines. There could be any number of OD lines, but always only 1 PO. The new array needs to be as follows:

Array
1.
PO|115207534
OD|115207534
2.
PO|115207535
OD|115207535
OD|115207536

What's the most efficient using only one foreach loop? And using 2 foreach loops?

Upvotes: 0

Views: 53

Answers (1)

Balaji Kandasamy
Balaji Kandasamy

Reputation: 4506

You can try like this to split the imported items as number of chunked arrays by the value "PO",

<?php
$array = array("PO", "OD", "PO", "OD", "OD", "OD", "OD", "PO", "OD", "PO", "OD", "OD");
$result = array();
$index = -1;
foreach ($array as $value) {
    if ($value == "PO") {
        $index++;
    }
    $result[$index][] = $value;
}
?>
<pre>
    <?php
    print_r($result);
    ?>    
</pre>

Output: http://codepad.org/aXpK43Uw

Upvotes: 1

Related Questions