根据默认索引将空索引动态添加到数组

时间:2020-08-22 09:38:46

标签: php arrays laravel

我有下面的数组,其中包含一组默认索引,这些索引必须出现在我的最终数组中:

'entities' => [
        'deliveredAt',
        'issuedAt',
        'totals' => [
            'due',
            'gross',
            'net',
            'tax' => [
                'amount',
                'net',
                'rate',
            ],
        ]
],

上面的数组保存在名为$entities的变量中。

现在,我有一个第三方API,该API将返回上述实体,但仅在该实体包含值的情况下才将它们包括在响应中。

例如,$response可能看起来像这样:

array:2 [▼
  "issuedAt" => "2020-08-20"
  "totals" => array:1 [▼
    "tax" => []
  ]
]

如您所见,如果将返回的数组与我期望的索引进行比较,则会缺少一些内容:

  • deliveredAt
  • totals.duetotals.grosstotals.nettotals.tax.amounttotals.tax.nettotals.tax.rate

我正在尝试制作一种可以遍历$response数组的方法,并检查它是否包含我期望的索引。如果没有,我只是想将索引设置为null

以下是我到目前为止的内容:

foreach ($entities as $key => $entity) {
         if (!is_array($entity)) {
             if (!isset($response[$entity])) {
                    $response[$entity] = null;
             }
         }
}

但是,这只会添加不是数组的索引。在此示例中,它将仅添加:deliveredAt => null

我该怎么办,因此上述方法可以遍历至少两个嵌套数组并添加索引名和null值?

2 个答案:

答案 0 :(得分:2)

您可以使用键和NULL(或任何您需要的)作为值来定义初始数组:

$entities = [
    'deliveredAt' => null,
    'issuedAt' => null,
    'totals' => [
        'due' => null,
        'gross' => null,
        'net' => null,
        'tax' => [
            'amount' => null,
            'net' => null,
            'rate' => null,
        ],
    ]
];

// here's your real data
$realData = [
  "issuedAt" => "2020-08-20",
  "totals" => [
    "tax" => [
      'net' => 42,    
    ]
  ]
];
// now use array_replace_recursive to replace keys in `$entities` with values of `$realData`
print_r(array_replace_recursive($entities, $realData));

Fiddle

还要注意,$realData中不存在的来自$entities的键将被添加到结果中。

答案 1 :(得分:1)

您可以使用array_replace_recursive来执行此操作。您只需稍微更改关联数组实体,因此每个属性都需要进行初始化(例如NULL或'')。

$result = array_replace_recursive($entities, $array);

您可以在这里进行测试http://sandbox.onlinephpfunctions.com/code/4688ed3240050479edeef7c9e4da16f98dbe01de

这是孔代码:

$array = [
  "issuedAt" => "2020-08-20",
  "totals" => [
    "tax" => [
        'amount' => 100
    ]
  ]
];

$entities = [
    'deliveredAt' => NULL,
    'issuedAt' => NULL,
    'totals' => [
        'due' => NULL,
        'gross' => NULL,
        'net' => NULL,
        'tax' => [
            'amount' => NULL,
            'net' => NULL,
            'rate' => NULL
        ],
    ]
];

$result = array_replace_recursive($entities, $array);
var_dump($result);