animaletdesequia
animaletdesequia

Reputation: 45

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.

Upvotes: 0

Views: 167

Answers (6)

CrayonViolent
CrayonViolent

Reputation: 32527

yet another approach, since you didn't really give an example of what you mean by "bidimensional" ...

$workers="name1:age1/name2:age2/name3:age3";
parse_str(rtrim(preg_replace('~name(\d+):([^/]+)/?~','name[$1]=$2&',$workers),'&'),$names);

output:

Array
(
    [name] => Array
        (
            [1] => age1
            [2] => age2
            [3] => age3
        )

)

Upvotes: 1

AbraCadaver
AbraCadaver

Reputation: 79014

This is another approach, not multidimensional:

parse_str(str_replace(array(':','/'), array('=','&'), $workers), $array);
print_r($array);

Shorter in PHP >= 5.4.0:

parse_str(str_replace([':','/'], ['=','&'], $workers), $array);
print_r($array);

Upvotes: 1

Nikolaos Dimopoulos
Nikolaos Dimopoulos

Reputation: 11485

The quick solution is

$results = [];
$data    = explode("/", $workers);
foreach ($data as $row) {
    $line = explode(":", $row);
    $results[] = [$line[0], $line[1]];
}

You could also use array_walk with a custom function which does the second level split for you.

Upvotes: 1

ops
ops

Reputation: 2049

Try this code:

<?php
$new_arr=array();
$workers="name1:age1/name2:age2/name3:age3";
$arr=explode('/',$workers);
foreach($arr as $value){
   $new_arr[]=explode(':',$value);
}
?>

Upvotes: 1

cornelb
cornelb

Reputation: 6066

$array = array();
$workers = explode('/', "name1:age1/name2:age2/name3:age3");

foreach ($workers as $worker) {
    $worker = explode(':', $worker);
    $array[$worker[0]] = $worker[1];
}

Upvotes: 1

GargantuChet
GargantuChet

Reputation: 5789

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++;
}

Upvotes: 1

Related Questions