首页 > 解决方案 > 将值添加到关联数组中,在循环 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 循环内添加?

标签: phparraysassociative-array

解决方案


推荐阅读