Search code examples
phparraysmultidimensional-arraysplitdelimited

Split a flat array into a 2d array with chunked rows when a delimiting element is encountered


I have array with ~ 10000 values.

Example:

  $arr = array("Name", "1.00", "87.70", "12.30",     
  "3.30", "3.30", "0.00", "3.50", "2.10", "1.11", "0.10", "14.00",
  "4.80", "0.00", "4.80", "0.00", "0.70", "44.00", "12.00", "85.00", 
  "138.00", "118.00", "0.10", "0.32", "1.00", "9.00", "40.00", "0.05", 
  "0.11", "0.04", "0.17", "0.10", "0.70", "5.00", "0.05", "0.40", 
  "1.00", "0.00", "65.00", "^_^", "Name2", "1.00", 
  "88.00", "12.00", "3.30", "3.30", "0.00", "3.20", "1.92", "1.01", 
  "0.08", "13.00", "4.80", "0.00", "4.80", "0.00", "0.70", "44.00", 
  "12.00", "85.00", "139.00", "118.00", "0.10", "0.32", "1.00", "9.00", 
  "36.00", "0.00", "0.10", "0.04", "0.17", "0.10", "0.70", "7.00", 
  "0.05", "0.40", "1.00", "0.00", "61.00", "^_^",

and so on....

I need to explode array when it reach value in array "^_^" and make array in array. And then I will and info into database.

I tried to explode, foreach and explode but didn't find a solution for this problem.


Solution

  • You will need to write your own function to do this. Here is a simple example that should explain it:

    function array_split($arr, $splitBy) {
        $result = [];
        $subArray = [];
    
        foreach ($arr as $elem) {
            // If an element matches your delimiter,
            // add the current sub-array to the result set and start a new sub-array
            // Else add the element to the sub-array
            if ($elem == $splitBy) {
                $result[] = $subArray;
                $subArray = [];
            } else {
                $subArray[] = $elem;
            }
        }
    
        // Make sure the last sub-array also gets added to the result set
        $result[] = $subArray;
    
        return $result;
    }