PHP - Make multi-dimensional associative array from a delimited string

前端 未结 4 481
故里飘歌
故里飘歌 2020-12-10 21:27

Can you turn this string:

\"package.deal.category\"

Into an array like this:

$array[\'package\'][\'deal\'][\'category\']


        
相关标签:
4条回答
  • 2020-12-10 21:54

    I know this was asked some time ago, but for anyone else looking for another possible answer that doesn't involve loops, try using JSON.

    To make $array['key1']['key2'] = $value

    $key = 'Key1.Key2';
    $delimiter = '.';
    $value = 'Can be a string or an array.';
    
    $jsonkey = '{"'.str_replace($delimiter, '":{"', $key).'":';
    $jsonend = str_repeat('}', substr_count($jsonkey, '{'));
    $jsonvalue = json_encode($value);
    $array = json_decode($jsonkey.$jsonvalue.$jsonend, true);
    
    0 讨论(0)
  • 2020-12-10 21:55

    Try this:

    $text = 'package.deal.category';
    
    $array = array();
    foreach(array_reverse(explode('.', $text)) as $key) $array = array($key => $array);
    
    print_r($array);
    
    0 讨论(0)
  • 2020-12-10 21:59

    I don't really understand, what the problem is with this?

    $parts = explode('.', $string);
    $array = array();
    
    while (!empty($parts)) {
        $array = array(array_pop($parts) => $array);
    }
    
    0 讨论(0)
  • 2020-12-10 22:06

    What have you tried? The absolute answer to this is very easy:

    $keys = explode('.', $string);
    $array = array();
    $arr = &$array;
    foreach ($keys as $key) {
       $arr[$key] = array();
       $arr = &$arr[$key];
    }
    unset($arr);
    

    ...but why would this be useful to you?

    0 讨论(0)
提交回复
热议问题