数组到数组的转换(增加维数和格式)

时间:2016-01-20 09:38:11

标签: php arrays

输入数组

$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:

  • 组的数量是动态的(用户输入)。例如,除了 “奥迪”和“福特”;也可能有“丰田”,“梅赛德斯”。
  • 每个组有3个子信息:1个名称,2个位置和3个数量 位置。
  • 输入中的序列始终相同。第1名,第2名,第3名 量。

  • 每个组在输入中都有正确的订单号。 (如 “group_name_ 1 或group_locations_ 4

备注2:我再次阅读了数组函数。并尝试了各种代码,但我甚至无法接近。

你能帮我吗?

3 个答案:

答案 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);

Demo