这是从数组输出。
[25.1] => Super Cylinder|2080
[25.2] => Main Post Powered Rotation|10780
[36.1] => Electric H-Frame Trolley|16630
[36.2] => Air Powered H-Frame Trolley|11028
我想要这样的输出如何获得此输出。 如何将关联的键值设置为将成为圆数的主键。
[25]=> Super Cylinder|2080,Main Post Powered Rotation|10780
[36]= > Electric H-Frame Trolley|16630, Air Powered H-Frame
我如何获得这样的数组值。
答案 0 :(得分:2)
使用常规foreach
循环的简短解决方案:
$arr = [
"25.1" => "Super Cylinder|2080",
"25.2" => "Main Post Powered Rotation|10780",
"36.1" => "Electric H-Frame Trolley|16630",
"36.2" => "Air Powered H-Frame Trolley|11028"
];
$result = [];
foreach ($arr as $k => $v) {
$rounded = round((int) $k);
(isset($result[$rounded]))? $result[$rounded] .= ', '. $v : $result[$rounded] = $v;
}
print_r($result);
输出:
Array
(
[25] => Super Cylinder|2080, Main Post Powered Rotation|10780
[36] => Electric H-Frame Trolley|16630, Air Powered H-Frame Trolley|11028
)
答案 1 :(得分:1)
您可以手动合并为:
<?php
$arr = array(
"25.1" => "Super Cylinder|2080",
"25.2" => "Main Post Powered Rotation|10780",
"36.1" => "Electric H-Frame Trolley|16630",
"36.2" => "Air Powered H-Frame Trolley|11028"
);
$ret = array();
foreach($arr as $key => $val){
$key_new = intval($key);
if(!isset($ret[$key_new])) $ret[$key_new] = array();
array_push($ret[$key_new], $val);
}
//print_r($ret);
//merge the values
foreach($ret as $key => &$val){
$val = implode(",", $val);
}
unset($val);
print_r($ret);
?>
这给出了:
Array
(
[25] => Super Cylinder|2080,Main Post Powered Rotation|10780
[36] => Electric H-Frame Trolley|16630,Air Powered H-Frame Trolley|11028
)