我有两个包含一些值的数组。
$type = array("first", "second", "third");
$date = array(
0 => "2019-04-30",
1 => "2019-05-01",
2 => "2019-05-02",
3 => "2019-05-03"
);
我需要输出如下内容:
[
type :first,
date: [
"2019-04-30": 1.2,
.....
]
]
但是由于某种原因,我没有采用这种格式。
这是我尝试过的代码。
$newArr = array();
foreach($type as $tt) {
$newArr[]['type'] = $tt;
$newDate = array();
foreach ($date as $d) {
$newDate[$d] = 1.2;
}
$newArr[]['date'] = $newDate;
}
任何人都可以证明我做错了什么。
谢谢。
答案 0 :(得分:3)
它只涉及构建数组,然后以正确的顺序添加它,这将构建所有数据并在循环结束时一口气添加它...
$newArr = array();
foreach($type as $tt) {
$newDate = array();
foreach ($date as $d) {
$newDate[$d] = 1.2;
}
$newArr[] = [ 'type' => $tt, 'date' => $newDate];
}
您可以将其缩短为这个长度,但这并没有太大的不同...
foreach($type as $tt) {
$newArr[] = [ 'type' => $tt, 'date' => array_fill_keys($date, 1.2)];
}
答案 1 :(得分:0)
让它变得更简单
$newArr = array();
$newdates = array();
foreach($dates as $date){
$newdates[$date] = 1.2;
}
foreach($type as $tt) {
$newArry[] = array("type"=>$tt,"date"=>$newdates);
}
答案 2 :(得分:0)
您可以使用array_map
和array_fill_keys
以获得所需的结果
$type = ["first", "second", "third"];
$date = [
0 => "2019-04-30",
1 => "2019-05-01",
2 => "2019-05-02",
3 => "2019-05-03"
];
$newArr = [];
array_map(function($t, $d) use ($date, &$newArr){
$newArr[] = [
'type' => $t,
'date' => array_fill_keys($date, 1.2)
];
}, $type, $date);