当我提交表单时,我得到数组格式的输出,如:
Array ( [quantity_2] => 2 [extra_2] => 1 [quantity_1] => 1 [quantity_3] => 5 [extra_3] => 1 )
我想根据数组键最后一个数字拆分此数组,如:
Array ( [quantity_2] => 2 [extra_2] => 1)
Array ( [quantity_1] => 1 [extra_2] => )
Array ( [quantity_3] => 5 [extra_3] => 1)
非常感谢您的宝贵回放。
答案 0 :(得分:0)
我不认为有一种方法可以创建多个数组,而无需逐一进行,所以最接近IMO的方法如下:
$arr = [
'quantity_2' => 2,
'extra_2' => 1,
'quantity_1' => 1,
'extra_1' => 10,
'quantity_3' => 213,
'extra_3' => 1
];
$newArray = [];
foreach ($arr as $key => $value) {
$split = explode('_', $key);
if (count($split) < 2) {
continue;
}
$newArray[$split[1]][$split[0]] = $value;
}
print_r($newArray);
它的作用: - 创建新的空数组 - 遍历所有元素 - 用下划线分割键,并使用第二部分作为id - 根据您想要/可能需要的格式填充新阵列 - 有一个新的结构化数组,看起来像这样:
Array
(
[2] => Array
(
[quantity] => 2
[extra] => 1
)
[1] => Array
(
[quantity] => 1
[extra] => 10
)
[3] => Array
(
[quantity] => 213
[extra] => 1
)
)
答案 1 :(得分:0)
我认为这个简单foreach
符合您的需求。
$input = [
'quantity_2' => 2,
'extra_2' => 1,
'quantity_1' => 1,
'quantity_3' => 5,
'extra_3' => 1
];
$output = [];
foreach ($input as $key => $value) {
list ($name, $id) = explode('_', $key);
$output[(int)$id][$key] = $value;
}
$output = array_values($output);
var_dump($output);
答案 2 :(得分:0)
对此做了一些假设,并且在任何错误检查中都没有添加,但它应该足以让你开始。
$arr = [
'quantity_1' => 1,
'extra_1' => 1,
'quantity_2' => 2,
'extra_2' => 2,
'quantity_3' => 3,
'extra_3' => 3
];
$formatted = [];
$pattern = '/_(\d)+$/';
$matches = null;
foreach ($arr as $key => $value) {
preg_match($pattern, $key, $matches);
$formatted[$matches[1]][$key] = $value;
}
print_r($formatted);
<强>输出:强>
Array
(
[1] => Array
(
[quantity_1] => 1
[extra_1] => 1
)
[2] => Array
(
[quantity_2] => 2
[extra_2] => 2
)
[3] => Array
(
[quantity_3] => 3
[extra_3] => 3
)
)