[英]Php array split based on array key name in
When I submit the form I get the output of array format like: 当我提交表单时,我得到如下数组格式的输出:
Array ( [quantity_2] => 2 [extra_2] => 1 [quantity_1] => 1 [quantity_3] => 5 [extra_3] => 1 )
I want to split this array based on array key last number like: 我想基于数组键的最后一个数字来拆分该数组,例如:
Array ( [quantity_2] => 2 [extra_2] => 1)
Array ( [quantity_1] => 1 [extra_2] => )
Array ( [quantity_3] => 5 [extra_3] => 1)
Many thanks for your valuable replay. 非常感谢您宝贵的重播。
I dont think there is a way to create multiple arrays without doing it one by one, so the closest you could get IMO is following: 我不认为有一种方法可以创建多个数组,而无需一个接一个地创建,因此可以得到的最接近的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);
What it does: - create new empty array - loop over all elements - split the key by underscore and use the second part as id - fill the new array according to the format you want/might want - have new structured array which looks like a so: 它的作用:-创建一个新的空数组-遍历所有元素-用下划线分隔键,并将第二部分用作id-根据您想要/可能想要的格式填充新数组-拥有一个看起来像一个新的结构化数组所以:
Array
(
[2] => Array
(
[quantity] => 2
[extra] => 1
)
[1] => Array
(
[quantity] => 1
[extra] => 10
)
[3] => Array
(
[quantity] => 213
[extra] => 1
)
)
I think this simple foreach
will suits your needs. 我认为这个简单的
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);
Made a fair few assumptions on this, and haven't added in any error checking but it should be enough to get you started. 对此做出了一些假设,并且没有添加任何错误检查,但这足以使您入门。
$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);
Output: 输出:
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
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.