Reputation: 23
convert this string:
animal,,lion|building,,large|animal,,giraffe|animal,,elephant|building,,small|weight,,120kg|building,,middle
to sorted array like this:
[animal] => [0] => lion
[1] => giraffe
[2] => elephant
[building] => [0] => large
[1] => small
[2] => middle
[weight] => [0] => 120kg
my solution:
$string = "animal,,lion|building,,large|animal,,giraffe|animal,,elephant|building,,small|weight,,120kg|building,,middle";
$array = explode('|', $string);
foreach($array as $k=>$v){
$array[$k] = explode(',,', $v);
}
but this only gives a nonsorted array:
Array
(
[0] => Array
(
[0] => animal
[1] => lion
)
[1] => Array
(
[0] => building
[1] => large
)
[2] => Array
(
[0] => animal
[1] => giraffe
)
[3] => Array
(
[0] => animal
[1] => elephant
)
[4] => Array
(
[0] => building
[1] => small
)
[5] => Array
(
[0] => weight
[1] => 120kg
)
[6] => Array
(
[0] => building
[1] => middle
)
)
Upvotes: 0
Views: 76
Reputation: 5371
$string = "animal,,lion|building,,large|animal,,giraffe|animal,,elephant|building,,small|weight,,120kg|building,,middle";
$array = explode('|', $string);
$newArray = array();
foreach($array as $k=>$v){
list($type,$val) = explode(',,', $v);
$newArray[$type][] = $val;
}
var_dump($newArray);
Result:
array(3) {
["animal"]=> array(3) {
[0]=> string(4) "lion"
[1]=> string(7) "giraffe"
[2]=> string(8) "elephant"
}
["building"]=> array(3) {
[0]=> string(5) "large"
[1]=> string(5) "small"
[2]=> string(6) "middle"
} ["weight"]=> array(1) {
[0]=> string(5) "120kg"
}
}
Upvotes: 1