search

Home  >  Q&A  >  body text

PHP master looks at an array problem

        [['7','2'],['8','2'],['11','2'],['10','2'],['9','2']]

The data inventory is such data ['7','2'] 7 represents the product id and 2 represents the quantity of the product purchased

Now how to restore it to an array that can be used by PHP?

高洛峰高洛峰2769 days ago885

reply all(7)I'll reply

  • 滿天的星座

    滿天的星座2017-06-08 11:03:38

    It’s a tricky method: Of course, the premise is that your data is complete and there will be no negative numbers, NULL or anything like that

    $a = "[['7','2'],['8','2'],['11','2'],['10','2'],['9','2']]";
    $result = array();
    preg_match_all("/'(\d*)'/", $a, $matches);
    for ($i = 0; $i < count($matches[1]); $i += 2){
       $result[(int)$matches[1][$i]] = (int) $matches[1][$i+1];
    }

    Personal test successful

    reply
    0
  • 大家讲道理

    大家讲道理2017-06-08 11:03:38

    You didn’t mention the specific format, so I’ll use the following format first

    $data = [['7','2'],['8','2'],['11','2'],['10','2'],['9','2']];
    $products = array();
    foreach ($data as $tmp) {
        $products[] = array(
            'id' => $tmp[0],
            'total' => $tmp[1]
        );
    }
    var_dump($products);

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-06-08 11:03:38

    Thanks for the invitation!

    This is an array, you can just loop it:

        $arr     = [['7','2'],['8','2'],['11','2'],['11','2'],['11','2']];
        var_dump($arr[0]);die;
        

    This array is equivalent to:

        $arr     = array(
                        array('7','2'),
                        array('8','2'),
                        array('11','2'),
                        array('11','2'),
                        array('11','2'),
                    );
         var_dump($arr[0]);die;

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-06-08 11:03:38

    If you deposit it like this, then it will be over if you undo it again.

    $str = json_encode(array(
        array(7, 2),
        array(8, 2),
    ));
    
    var_dump(json_decode($str));

    reply
    0
  • 迷茫

    迷茫2017-06-08 11:03:38

    Standard json requires double quotes, so just convert the single quotes into double quotes and then json_decode

    $sqldata = "[['7','2'],['8','2'],['11','2'],['10','2'],['9','2']]";
    $sqldata = str_replace('\'', '\"', $sqldata );
    $data = json_decode($sqldata);
    echo $data[0][1]; // >> 2

    reply
    0
  • 女神的闺蜜爱上我

    女神的闺蜜爱上我2017-06-08 11:03:38

    $str = "[['7','2'],['8','2'],['11','2'],['10','2'],['9','2']]";
    var_dump(eval('return '.$str.';'));

    Try it

    reply
    0
  • 三叔

    三叔2017-06-08 11:03:38

    json_decode() 

    reply
    0
  • Cancelreply