phpmultidimensional-arrayexplodetext-parsing

Explode a string with two delimiters into an array


I'm trying to build a bi-dimensional array from a string. The string has this structure:

$workers = "name1:age1/name2:age2/name3:age3";

The idea is to explode the array into "persons" using "/" as separator, and then using ":" to explode each "person" into an array that would contain "name" and "age".

I know the basics about the explode function:

$array = explode("separator", "$string");

But I have no idea how to face this to make it bidimensional.


Solution

  • Something like the following should work. The goal is to first split the data into smaller chunks, and then step through each chunk and further subdivide it as needed.

    $row = 0;
    foreach (explode("/", $workers) as $substring) {
        $col = 0;
        foreach (explode(":", $substring) as $value) {
            $array[$row][$col] = $value;
            $col++;
        }
        $row++;
    }