输入数组
$input = array (
"group_name_1" => "audi",
"group_locations_1" => "tokyo,barcelona,paris",
"group_quantities_at_locations_1" => "1,2,7",
"group_name_2" => "ford",
"group_locations_2" => "london,prag",
"group_quantities_at_locations_2" => "3,6"
);
需要输出表格
$target_output = array (
"audi" => array ( "tokyo" => 1, "barcelona" => 2, "paris" => 7 ),
"ford" => array ( "london" => 3, "prag" => 6 )
);
备注1:
输入中的序列始终相同。第1名,第2名,第3名 量。
每个组在输入中都有正确的订单号。 (如 “group_name_ 1 或group_locations_ 4 )
备注2:我再次阅读了数组函数。并尝试了各种代码,但我甚至无法接近。
你能帮我吗?答案 0 :(得分:1)
<?php
$inputs = array (
"group_name_1" => "audi",
"group_locations_1" => "tokyo,barcelona,paris",
"group_quantities_at_locations_1" => "1,2,7",
"group_name_2" => "ford",
"group_locations_2" => "london,prag",
"group_quantities_at_locations_2" => "3,6"
);
$result = array();
foreach ($inputs as $key => $value) {
if (!preg_match('/group_name_([0-9]*)/', $key, $matches)) {
continue;
}
$locations = explode(',', $inputs['group_locations_' . $matches[1]]);
$quantities = explode(',', $inputs['group_quantities_at_locations_' . $matches[1]]);
$result[$value] = array_combine($locations, $quantities);
}
echo '<pre>';
var_dump($result);
echo '</pre>';
答案 1 :(得分:1)
假设group_name_x, group_locations_x and group_quantities_at_locations_x
数组
$input
个密钥
$input = array(
"group_name_1" => "audi",
"group_locations_1" => "tokyo,barcelona,paris",
"group_quantities_at_locations_1" => "1,2,7",
"group_name_2" => "ford",
"group_locations_2" => "london,prag",
"group_quantities_at_locations_2" => "3,6"
);
$new_array = array();
foreach ($input as $key => $val) {
if (strpos($key, 'group_name') !== false) {
$new_array[$val] = array();
$group_no = $key[strlen($key) - 1];
$location_array = explode(',', $input["group_locations_{$group_no}"]);
$group_quantities_array = explode(',', $input["group_quantities_at_locations_{$group_no}"]);
$new_array[$val] = array_combine($location_array, $group_quantities_array);
}
}
print_r($new_array);
<强>输出:强>
Array
(
[audi] => Array
(
[tokyo] => 1
[barcelona] => 2
[paris] => 7
)
[ford] => Array
(
[london] => 3
[prag] => 6
)
)
答案 2 :(得分:0)
您可以像{/ p>一样使用array_walk
$result = [];
$chunked = array_chunk($input,3);
array_walk($chunked,function($v) use (&$result){
$result[$v[0]] = array_combine(explode(",",$v[1]),explode(",",$v[2]));
});
print_R($result);