将字符串转换为格式化的数组

时间:2019-07-02 15:44:32

标签: php arrays

我正在尝试将序列化的字符串转换为数组

这是我在php上获取的字符串(使用序列化AJAX POST发送的表单)

"ref_1=000CBA0000&name_1=Produto%20A&quantity_1=1&ref_2=000CBA0000&name_2=Produto%20A&quantity_2=1&ref_3=000CBA0000&name_3=Produto%20A&quantity_3=1"

字符串中的每个产品都有其自己的引用,名称,数量,因此当前我的字符串中包含3个产品的信息,它可能会更改每个请求。

我正在尝试将序列化的字符串转换为这种格式的数组

[
    [1]
        ref => <copy the value from ref_1>
        name => <copy the value from name_1>
        quantity => <copy the value from quantity_1>
    [2]
        ref => <copy the value from ref_2>
        name => <copy the value from name_2>
        quantity => <copy the value from quantity_2>

    [3] 
        ref => <copy the value from ref_3>
        name => <copy the value from name_3>
        quantity => <copy the value from quantity_3>
]

所以以后我可以做一个 foreach 产品并单独获取。

我尝试用以下方式分解字符串:

$array = explode("&",$string);
var_dump($array);

但这给了我不同的结果:

array(9) { [0]=> string(16) "ref_1=000CBA0000" [1]=> string(21) "name_1=Produto%20A" [2]=> string(12) "quantity_1=1" [3]=> string(16) "ref_2=000CBA0000" [4]=> string(21) "name_2=Produto%20A" [5]=> string(12) "quantity_2=1" [6]=> string(16) "ref_3=000CBA0000" [7]=> string(21) "name_3=Produto%20A" [8]=> string(12) "quantity_3=1" }

2 个答案:

答案 0 :(得分:3)

您可以使用parse_str()解析参数,然后循环访问数组和explode()键,以分别获取键名和键号。

(NrBL, LgnBL, Niveau, clientNr)

礼物:

parse_str("ref_1=000CBA0000&name_1=Produto%20A&quantity_1=1&ref_2=000CBA0000&name_2=Produto%20A&quantity_2=1&ref_3=000CBA0000&name_3=Produto%20A&quantity_3=1", $arr);


foreach($arr as $key => $val){
    $temp = explode("_", $key);
    $new[$temp[1]][$temp[0]] = $val;
}
var_dump($new);

https://3v4l.org/WVGiv

正如Cid所提到的,只要键名中的下划线按名称和数字的顺序将其分开,这将起作用。
如果没有,它将失败。

答案 1 :(得分:2)

这是一个代码,它将执行您所要求的内容,而不管您的字符串有多少个参数(以什么顺序排列):

$string = "ref_1=000CBA0000&name_1=Produto%20A&quantity_1=1&ref_2=000CBA0000&name_2=Produto2%20A&quantity_2=2&ref_3=000CBA0000&name_3=Produt3o%20A&quantity_3=3";

parse_str($string, $paramsArray);

$result = [];

foreach ($paramsArray as $key => $item) {
    if (strpos($key, 'ref_') !== false) {
        $itemNumber = substr($key, strpos($key, "ref_") - 1);
        $result[] = [
          'ref' => $key,
          'name' =>  $paramsArray['name_'.$itemNumber],
          'quantity' =>  $paramsArray['quantity_'.$itemNumber],
        ];

    }
}

结果您将需要使用以下格式:

[
    [1]
        ref => <copy the value from ref_1>
        name => <copy the value from name_1>
        quantity => <copy the value from quantity_1>
    [2]
        ref => <copy the value from ref_2>
        name => <copy the value from name_2>
        quantity => <copy the value from quantity_2>

    [3] 
        ref => <copy the value from ref_3>
        name => <copy the value from name_3>
        quantity => <copy the value from quantity_3>
]
相关问题