PHP master looks at an array problem
高洛峰
高洛峰 2017-06-08 11:01:38
0
7
856
        [['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?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(7)
滿天的星座

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

大家讲道理

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);
淡淡烟草味

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;
phpcn_u1582

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));
迷茫

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
女神的闺蜜爱上我
$str = "[['7','2'],['8','2'],['11','2'],['10','2'],['9','2']]";
var_dump(eval('return '.$str.';'));

Try it

三叔
json_decode() 
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template