我有以下数组:
$arr = array(
array("2014-03-13"=>array("a"=>1,"b"=>2)),
array("2014-03-12"=>array("a"=>4,"b"=>3))
);
我希望它看起来更像这样。
$arr = array(0=>array("date"=>"2014-03-13","a"=>1,"b"=>2),
1=>array("date"=>"2014-03-12","a"=>4,"b"=>3));
这是我到目前为止写的。
$keys = array();
$vals = array();
foreach($arr as $row){
foreach($row as $key=>$val){
$keys[]=array("date"=>$key);
foreach($val as $keys=>$values){
$vals[]=array($keys=>$values);
}
}
}
获得dates
的array
工作良好,因此在下面的示例中,$keys array
工作,但是$vals array
不按预期工作,而是给了我一个类似的数组。
Array ( [0] => Array ( [a] => 1 )
[1] => Array ( [b] => 2 )
[2] => Array ( [a] => 4 )
[3] => Array ( [b] => 3 )
[4] => Array ( [a] => 4 )
[5] => Array ( [b] => 3 ) )
应该是
$result = array();
foreach($arr as $row) {
foreach($row as $date=>$values) {
$values['date'] = $date;
$result[] = $values;
}
}
$arr = array(
array(
"2014-03-13" => array("a"=>1, "b"=>2)
),
array(
"2014-03-12" => array("a"=>4, "b"=>3)
),
);
$result = array();
foreach ($arr as $item) {
foreach ($item as $date => $values) {
$result[] = array_merge(array('date' => $date), $values);
}
}
var_dump($result);
Here is the code:
$arr = array(
0=>array("2014-03-13"=>array("a"=>1,"b"=>2)),
array("2014-03-12"=>array("a"=>4,"b"=>3))
);
$finalarray=array();
foreach($arr as $k=>$v){
foreach($v as $kk=>$vv){
$newarray=array();
$newarray["date"]=$kk;
foreach($vv as $kkk=>$vvv){
$newarray[$kkk]=$vvv;
}
}
$finalarray[]=$newarray;
}
echo "<pre>";
print_r($finalarray);
echo "</pre>";
**Here is the output:**
Array
(
[0] => Array
(
[date] => 2014-03-13
[a] => 1
[b] => 2
)
[1] => Array
(
[date] => 2014-03-12
[a] => 4
[b] => 3
)
)