我有一个数组,但我不知道如何将其更改为我需要的结构:我的数组: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 回答
素胚勾勒不出你
TA贡献1827条经验 获得超9个赞
使用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);
- 1 回答
- 0 关注
- 137 浏览
添加回答
举报
0/150
提交
取消