How to convert string to array?

前端 未结 2 668
醉话见心
醉话见心 2020-12-21 17:59

I need to convert string

\"name1\", \"b\", \"2\", \"name2\", \"c\", \"3\", \"name3\", \"b\", \"2\", ....

to an array like

$         


        
相关标签:
2条回答
  • 2020-12-21 18:31
    $input = '"name1", "b", "2", "name2", "c", "3", "name3", "b", "2"';
    $input = str_replace('"', '', $input);
    $input = explode(', ', $input);
    
    $output = array();
    $i = 0;
    while ($i < count($input)) {
        $output[] = array(
            'name' => $input[$i++],
            'char' => $input[$i++],
            'qnt' => $input[$i++]
        );
    }
    
    print_r($output);
    

    Output:

    Array
    (
        [0] => Array
            (
                [name] => name1
                [char] => b
                [qnt] => 2
            )
    
        [1] => Array
            (
                [name] => name2
                [char] => c
                [qnt] => 3
            )
    
        [2] => Array
            (
                [name] => name3
                [char] => b
                [qnt] => 2
            )
    
    )
    
    0 讨论(0)
  • 2020-12-21 18:31

    If you do not care about the array keys being numeric, you can do:

    $string = 'name1, b, 2, name2, c, 3, name3, b, 2';
    print_r( array_chunk( explode(',', $string), 3 ) );
    
    0 讨论(0)
提交回复
热议问题