我尝试将数组类型从$ data转换为$ data2,但没有成功。
在$data
数组中,根据日期放置所有值。
但是$data2
值根据标题放置。
我想知道它是否是可转换数组。
$data['Group1']['Date1']['Empty'] = 5;
$data['Group1']['Date1']['Reservated'] = 1;
$data['Group1']['Date1']['WillReturn'] = 3;
$data['Group1']['Date1']['Remains'] = 1;
$data['Group1']['Date2']['Empty'] = 2;
$data['Group1']['Date2']['Reservated'] = 2;
$data['Group1']['Date2']['WillReturn'] = 3;
$data['Group1']['Date2']['Remains'] = -3;
$data['Group2']['Date1']['Empty'] = 0;
$data['Group2']['Date1']['Reservated'] = 1;
$data['Group2']['Date1']['WillReturn'] = 3;
$data['Group2']['Date1']['Remains'] = -4;
$data['Group2']['Date2']['Empty'] = 10;
$data['Group2']['Date2']['Reservated'] = 1;
$data['Group2']['Date2']['WillReturn'] = 1;
$data['Group2']['Date2']['Remains'] = 8;
$data2 = [
'Group1' => [
[ 'Title' => 'Empty',
'Date1' => 5,
'Date2' => 2,
],
[ 'Title' => 'Reservated',
'Date1' => 1,
'Date2' => 2,
],
[ 'Title' => 'WillReturn',
'Date1' => 3,
'Date2' => 3,
],
[ 'Title' => 'Remains',
'Date1' => 1,
'Date2' => -3,
],
// etc...
],
'Group2' => [
[ 'Title' => 'Empty',
'Date1' => 0,
'Date2' => 10,
],
[ 'Title' => 'Reservated',
'Date1' => 1,
'Date2' => 1,
],
[ 'Title' => 'WillReturn',
'Date1' => 3,
'Date2' => 1,
],
[ 'Title' => 'Remains',
'Date1' => -4,
'Date2' => -8,
],
// etc...
],
// etc...
];
有些人试试这里:
$new = [];
$grp = array_keys($datax);
$i =0;
foreach($datax as $key => $val)
{
$dates = array_keys($val);
foreach($val as $k=>$v)
{
$cases = array_keys($v);
$caseAndVals[$i]=$v;
$i++;
}
}
$z =0;
$y = 0;
foreach($grp as $g)
{
foreach($cases as $c)
{
$new[$g][$z]['Title']=$c;
foreach($dates as $d)
{
$new[$g][$z][$d] = 'values which correspond to the date and title';
}
$z++;
}
}
我根据小组和案例转换了数组,但我没有成功将值对应日期......
答案 0 :(得分:1)
你非常接近。
要获取values which correspond to the date and title
,请使用$data[$g][$d][$c]
。
每次通过$z
循环时,您需要将0
重置为$grp
,以便在每个组数组上获得正确的索引。
$new = array();
$grp = array_keys($data);
foreach($data as $key => $val)
{
$dates = array_keys($val);
foreach($val as $k=>$v)
{
$cases = array_keys($v);
$caseAndVals[]=$v;
}
}
foreach($grp as $g)
{
$z = 0;
foreach($cases as $c)
{
$new[$g][$z]['Title']=$c;
foreach($dates as $d)
{
$new[$g][$z][$d] = $data[$g][$d][$c];
}
$z++;
}
}