php - 将值添加到关联数组中,在循环 PHP 之后消失了 for 循环
问题描述
我有两个 for 循环,它们都创建了一个关联数组。我需要将第二个数组添加到第一个数组中。这是我的第一个数组的简单版本
'location' => 'some location'
'color' => 'some color'
'data' =>
array (size=3)
'id' => 1
'name' => 'Name'
'date' => 'some date'
'qty' => null
创建第一个数组的代码:
$data = [];
$addedData = array();
foreach ($dataColors as $dataColor) {
foreach ($existingData as $ed) {
if ($ed['location_id'] === $location && $ed['color_id'] === $dataColor && !in_array($ed['species_id'], $addedData)) {
array_push($addedData, $ed['species_id']);
$data[] = array(
'location' => $ed['location_id'],
'color' => $ed['color_id'],
'data' => $app['data_manager']->findOne(array('id' => $ed['species_id'])),
'qty' => NULL
);
}
}
}
现在我需要将第二个数组添加到qty
每个创建数组的键中。这是我尝试过的:
foreach ($data as $key => $value) {
$newData = [];
foreach ($dataFromDatabase as $dfd) {
if ($value['location'] === $dfd['location_id'] && $value['color'] === $dfd['color_id'] && $value['data']['id'] === $dfd['id']) {
$newData[] = array(
'week' => (int)date('W', strtotime($dfd['date'])),
'qty' => (int)$dfd['qty']
);
}
}
$value[$key]['qty'] = $newData;
var_dump($value); // this schows the that the data is added to the array
}
var_dump($data); // this doesn't show the added data
添加到数组的数据怎么可能不是在 for 循环之后添加,而是在 for 循环内添加?
解决方案
推荐阅读
- java - Spring Boot WebFluxTest 测试,无法实例化存储库,指定的类是一个接口
- javascript - 通过javascript提交HTML表单并防止默认
- assembly - NASM 赋值
- c# - Microsoft Graph API 不准确的错误消息
- python - 基本 Python - 通过 input() 将硬编码的 int 变量与动态 int 变量进行比较时,无法使 IF 语句工作
- save - RuntimeError:用于酸洗的未知 IValue 类型:设备
- python - 泛型工厂
- javascript - Element.scrollHeight 和 Element.scrollTop 每次被调用时都会计算返回值吗?
- c - Visual Studio 2019:强制包含文件不起作用?
- python - “解包”熊猫数据框的最快方法