Explode a string into a 2d array
Lets say I had a string like this.
apple:paper:red,pear:rock:blue,peach:scissors:green
How would you explode this into a multidimensional array? Could you do a nested split loop? Something like split the string on the comma and then again on the colon inside a loop. How do you use explode in this manner? I must be missing something obvious. The end result should be something like.
[0][0] = apple [0][1] = pear [0][2] = peach
[1][0] = paper [1][1] = rock [1][2] = scissors
[开发者_开发百科2][0] = red [2][1] = blue [2][2] = green
Thanks.
You can call explode multiple times:
$string = 'apple:paper:red,pear:rock:blue,peach:scissors:green';
$result = array();
foreach (explode(',', $string) as $piece) {
$result[] = explode(':', $piece);
}
Give this a go:
$string = 'apple:paper:red,pear:rock:blue,peach:scissors:green';
foreach (explode(',', $string) as $key=>$piece) {
foreach (explode(':', $piece) as $k=>$column) {
$result[$key][$k] = $column;
}
}
May help to make it come out as you want. (I've tested and it works for me ;))
精彩评论