Turn into a mass



  • There are such entry data:

    $key = "level1[level2][level3]";
    $val = ["foo", "bar"];
    

    We need to convert the key into this kind of thing:

    $result = [
        "level1" => [
            "level2" => [
                "level3" => ["foo", "bar"]
            ]
        ]
    ];
    

    How do you do that? Maybe there's some sort of built-in or library function?



  • There's no ready function, obviously you need to write yourself. If it's right under such conditions, it's like that.

    <?php
    $key = "level1[level2][level3]";
    $val = ["foo", "bar"];
    

    function apply( $matches, $val ) {
    $result = [];
    if ( is_array( $matches ) && count( $matches ) > 0 ) {
    $key = $matches[0][0];
    array_shift( $matches );
    $result[$key] = apply( $matches, $val );
    } else { $result = $val; }
    return $result;
    }
    if ( preg_match_all("/(\S+?)[(\S+)][(\S+)]/", $key, $matches) && is_array($matches) && count($matches) > 1 ) {
    array_shift( $matches );
    $result = apply( $matches, $val );
    }
    var_dump( $result );

    Outcome

    ***


Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2