Search code examples
phparraysstringexplodedelimited

Explode a string into a multidimensional array based on 4 different delimiters which signal how levels are separated


I want to explode a string with different kind of characters.

I already know how to explode a string, I also think I know how I can do it in different levels.

How do you use one of the values as name ($var['name']) instead of having numbers ($var[0])?

I only know how to do this manually in the array, but I don't know how to add it with variables.

In summary I want this string:

title:hello;desc:message|title:lorem;desc:ipsum;ids:1,2,3

to become this array:

[
    [
        'title' => 'hello',
        'desc' => 'message',
    ],
    [
        'title' => 'lorem',
        'desc' => 'ipsum',
        'ids' => ['1', '2', '3'],
    ],
]

Edit: I made some progress, but it's not quite finished.

<?php
$string = "title:hello;desc:message|title:lorem;desc:ipsum;ids:1,2,3";
$string = explode("|", $string);
foreach($string as $split){
    $split = explode(";", $split);
    foreach($split as $split2){
        $split2 = explode(":", $split2);
        // more code..
    }
}

Now I need $split2[0] to be the name and $split2[1] to be the value, like the example earlier.


Solution

  • $input = "title:hello;desc:message|title:lorem;desc:ipsum;ids:1,2,3";
    $items = preg_split("/\|/", $input);
    $results = array();
    $i = 0;
    foreach($items as $item){
         $subItems = preg_split("/;/", $item);
         foreach($subItems as $subItem){
            $tmp = preg_split("/:/", $subItem);
            $results[$i][$tmp[0]] = $tmp[1];
         } 
         $i++;
    
    }
    

    It returns:

    array(2) {
      [0]=>
      array(2) {
        ["title"]=>
        string(5) "hello"
        ["desc"]=>
        string(7) "message"
      }
      [1]=>
      array(3) {
        ["title"]=>
        string(5) "lorem"
        ["desc"]=>
        string(5) "ipsum"
        ["ids"]=>
        string(5) "1,2,3"
      }
    }
    

    And then process your 'ids' index