将字符串转换为排序数组

时间:2015-10-16 23:52:56

标签: php arrays string

转换此字符串:

动物,,狮子|建筑物,,大|动物,,长颈鹿|动物,,大象|建筑物,,小|重量,,120公斤|建筑物,,中间

排序数组如下:

[animal] => [0] => lion
            [1] => giraffe
            [2] => elephant

[building] => [0] => large
              [1] => small
              [2] => middle

[weight] => [0] => 120kg

我的解决方案:

$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);
}

但这仅提供非排序数组:

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
        )

)

1 个答案:

答案 0 :(得分:1)

$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);

结果:

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" 
  } 
}