0

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
        )

)
1
  • You don't have any sorting. Think about creating another array. Commented Oct 16, 2015 at 23:56

1 Answer 1

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

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" 
  } 
}
Sign up to request clarification or add additional context in comments.

2 Comments

That's a great comment, but downvoting answers simply because you don't like the question, or why the question is being asked, isn't the solution.
Your answer isn't sorting, it works because the first level indices are already in order.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.