创建一个数组,从一个字符串,有一个特定的字符串多次出现PHP


create an array from a string that has a multiple occurances of a certain string PHP

我有string1变量:

$string1 = category=123&code=456&type=type111&type=type222

如何创建一个数组从一个字符串,有string1变量的多次出现?

Array(
    array(
        [category] => 123
        [code] => 456
        [type] => type111
    ),
    array(
        [category] => 123
        [code] => 456
        [type] => type222
    )
)

这是解决方案,有点乱,但有效:

<?php
$string = "category=123&code=456&type=type111&type=type222";
$repeated_key = 'type';
$variable = explode('&', $string);
$data_o = array();
foreach ($variable as $key0 => $value0) {
$subvariable = explode('=', $value0);
if($subvariable[0] == $repeated_key){
    continue;
}
$data_o[$subvariable[0]] = $subvariable[1];
}
$i=0;
foreach ($variable as $key1 => $value1) {
$subvariable = explode('=', $value1);
if($subvariable[0] != $repeated_key){
    continue;
}
$data_t = array();
$data_t['type'] = $subvariable[1];
$data[] = array_merge($data_o,$data_t);
$i++;
}
echo "<pre>";
print_r($data);
exit;
?>