Mooseman
Mooseman

Reputation: 18891

Double explode an array

The string:

user:hello,user2:world

Desired Output:

$string = array(
   1 => array( 1 => "user", 2 => "hello"),
   2 => array( 1 => "user2", 2 => "world")
);

What I've tried (that doesn't work):

$string = explode(',',$string);
$string = explode(':',$string);

The error I get: explode() expects parameter 2 to be string
How can I get from the string to the desired output? Thanks!

Upvotes: 2

Views: 7648

Answers (4)

mpyw
mpyw

Reputation: 5754

<?php

$string = "user:hello,user2:world";

$array = array_map(function ($input) {
    return explode(':',$input);
}, explode(',', $string));

print_r($array);

Upvotes: 5

tahoe_sasquatch
tahoe_sasquatch

Reputation: 86

Please try this:

$string = 'user:hello,user2:world';
$output = explode(',',$string);
foreach ($output as &$e) {
    $e = explode(':', $e);
}
print_r($output);

Upvotes: 3

Jonathan Kuhn
Jonathan Kuhn

Reputation: 15311

loop over the output from the first explode and explode the second time on each value.

$string = "user:hello,user2:world";
$array = explode(',', $string);

foreach($array as $k=>$v){
    $array[$k] = explode(':', $v);
}

Upvotes: 6

sectus
sectus

Reputation: 15464

You can use example of user from manual.

function multiexplode ($delimiters,$string) {
    $ary = explode($delimiters[0],$string);
    array_shift($delimiters);
    if($delimiters != NULL) {
        foreach($ary as $key => $val) {
             $ary[$key] = multiexplode($delimiters, $val);
        }
    }
    return  $ary;
}

// Example of use
$string = "1-2-3|4-5|6:7-8-9-0|1,2:3-4|5";
$delimiters = Array(",",":","|","-");

$res = multiexplode($delimiters,$string);
echo '<pre>';
print_r($res);
echo '</pre>';

Upvotes: 0

Related Questions