build multidimensional array from string php

前端 未结 4 1504
我在风中等你
我在风中等你 2021-01-03 13:20

EDIT: Here is a portion of $preparedstring:

555555,Jones,Brian,NYC,1000,2011-10-21 00:00:00,Check,1542,0, ,Check, ,0, ,Check, ,; 666666

4条回答
  •  情话喂你
    2021-01-03 13:53

    Your approach to solving the problem is sadly very wrong, though there are many solutions to your problem, I would use something like the below.


    How does the code work?

    First we use explode to split our string up in smaller chunks, ; is our delimiter.

    We pass this newly created array to array_map as it's second parameter.

    array_map takes two parameters, the first one is a function that will be called for every member of the second paramater (which should be an array).

    Inside our callback to array_map we use explode to once again split out the values, now with , as our delimiter.


    $data = "1,2,3;4,5,6;7,8,9";
    
    $ret = array_map (
      function ($_) {return explode (',', $_);},
      explode (';', $data)
    );
    
    print_r ($ret);
    

    output

    Array
    (
        [0] => Array
            (
                [0] => 1
                [1] => 2
                [2] => 3
            )
    
        [1] => Array
            (
                [0] => 4
                [1] => 5
                [2] => 6
            )
    
        [2] => Array
            (
                [0] => 7
                [1] => 8
                [2] => 9
            )
    
    )
    

    It doesn't work, why?

    Probably because you are using a version of PHP prior to 5.3, if so you can use this snippet instead:

    function explode_by_comma ($_) {
      return explode (',', $_);
    }
    
    $ret = array_map ('explode_by_comma', explode (';', $data));
    

提交回复
热议问题