更改数组的结构(在数组中创建嵌套数组)

时间:2019-09-06 11:47:01

标签: php

我有一个数组,但不知道如何将其更改为所需的结构: 我的阵列:

array (
  "1536" => "12",
  "1695" => "Korea",
  "1904" => "10/7",
  "1905" => "",
  "1906" => null,
  "1907" => "1.1",
  "1906.1" => "H1",
  "1906.2" => "H35",
  "1905.1" => "15"
)

我需要将此数组转换为这种形式(删除数字的十分之一,然后将相同数字的值粘贴到数组中):

array (
  "1536" => "12",
  "1695" => "Korea",
  "1904" => "10/7",
  "1905" => array("", "15"),
  "1906" => array(null, "H1", "H35"),
  "1907" => "1.1"
)

1 个答案:

答案 0 :(得分:1)

使用array_walk()在数组上进行迭代。在迭代检查天气的每个周期中,密钥已经存在于$res数组中。如果存在,则创建与旧值合并的数组并分配给相同的键。如果尚不存在密钥,则将$val分配给$res数组。

$data = array("1536" => "12","1695" => "Korea","1904" => "10/7","1905" => "", "1906" => null,"1907" => "1.1","1906.1" => "H1","1906.2" => "H35","1905.1" => "15");

$res = array();
array_walk($data, function($val, $key) use(&$res) {
    $key = intval($key);
    if (array_key_exists($key, $res)) {
        $res[$key] = is_array($res[$key]) ? array_merge($res[$key], [$val]) : array_merge([$res[$key]], [$val]);
    } else {
        $res[$key] = $val;
    }
});

print_r($res);

工作demo