我在php下面有一个多维数组。
$resultdata[0] = array(
"daynumber" => 15,
"dayname" =>'Tue',
"infomation" => array('baller', 'ROller')
);
$resultdata[1] = array(
"daynumber" => 15,
"dayname" =>'Tue',
"infomation" => array('nomal', 'Goildt')
);
$resultdata[2] = array(
"daynumber" => 24,
"dayname" =>'Thur',
"infomation" => array('Volley', 'Foller')
);
我想结合相似的日期来形成以下结果。
$resultdata[0] = array(
"daynumber" => 15,
"dayname" =>'Tue',
"infomation" => array('baller', 'ROller'), array('nomal', 'Goildt')
);
$resultdata[1] = array(
"daynumber" => 24,
"dayname" =>'Thur',
"infomation" => array('Volley', 'Foller')
);
提前完成
我尝试使用此代码,但它要求我将数组转换为我不想要的字符串
function combineAndIgnore($result_arr){
$arr = array();
foreach($result_arr as $val){
$item = $val[$key];
foreach($val as $k=>$v){
$arr[$item][$k][] = $v;
}
}
// Combine unique entries into a single array
// and non-unique entries into a single element
foreach($arr as $key=>$val){
foreach($val as $k=>$v){
$field = array_unique($v);
if(count($field) == 1){
$field = array_values($field);
$field = $field[0];
$arr[$key][$k] = $field;
} else {
$arr[$key][$k] = $field;
}
}
}
return $arr;
}
答案 0 :(得分:1)
我屈服于转换为sting选项,无论如何都是
Array
(
[0] => Array
(
[daynumber] => 15
[dayname] => Tue
[infomation] => Array
(
[0] => Array
(
[0] => baller
[1] => ROller
[2] =>
[3] => gtk
)
[1] => Array
(
[0] => nomal
[1] => Goildt
)
)
)
[1] => Array
(
[daynumber] => 24
[dayname] => Thur
[infomation] => Array
(
[0] => Volley
[1] => Foller
)
)
)
RESULT
sw-precache
答案 1 :(得分:0)
以下是您的 唯一 用例的快速解决方案,您也可以使用Quick-T3st here:
<?php
$strJson = '[
{
"daynumber" :15,
"dayname" :"Tue",
"infomation" :["baller","ROller"]
},
{
"daynumber" :15,
"dayname" :"Tue",
"infomation" :["nomal","Goildt"]
},
{
"daynumber" :24,
"dayname" :"Thur",
"infomation" :["Volley","Foller"]
}
]';
function arrayBlend($jsonData){
$resultData = json_decode($jsonData, true);
$arrAll = [];
foreach($resultData as $data){
if(is_array($data)){
$arrAll[] = $data;
}
}
foreach($arrAll as $iCount=>&$arr){
$dayNum = $arr['daynumber'];
$dayName = $arr['dayname'];
$prev = ($iCount>0) ? $arrAll[$iCount-1] : null;
if($prev['daynumber'] == $dayNum && $prev['dayname'] == $dayName){
$arr['infomation'] = [ $prev['infomation'], $arr['infomation']];
unset($arrAll[$iCount-1]);
}
}
return $arrAll;
}
var_dump( arrayBlend($strJson) );
以上
var_dump()
:
array:2 [
1 => array:3 [
"daynumber" => 15
"dayname" => "Tue"
"infomation" => array:2 [
0 => array:2 [
0 => "baller"
1 => "ROller"
]
1 => array:2 [
0 => "nomal"
1 => "Goildt"
]
]
]
2 => array:3 [
"daynumber" => 24
"dayname" => "Thur"
"infomation" => array:2 [
0 => "Volley"
1 => "Foller"
]
]
]