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

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


'entities' => [

        'deliveredAt',

        'issuedAt',

        'totals' => [

            'due',

            'gross',

            'net',

            'tax' => [

                'amount',

                'net',

                'rate',

            ],

        ]

],

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


现在,我有一个第 3 方 API,它将返回上述实体,但仅当实体包含值时才将它们包含在响应中。


例如,a$response可以如下所示:


array:2 [▼

  "issuedAt" => "2020-08-20"

  "totals" => array:1 [▼

    "tax" => []

  ]

]

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


deliveredAt

totals.due, totals.gross, totals.net, totals.tax.amount, totals.tax.net, totals.tax.rate

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


以下是我到目前为止所拥有的:


foreach ($entities as $key => $entity) {

         if (!is_array($entity)) {

             if (!isset($response[$entity])) {

                    $response[$entity] = null;

             }

         }

}

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


我该怎么做,以便上述方法可以迭代多个至少 2 个嵌套数组并添加索引名称和null值?


小怪兽爱吃肉
浏览 72回答 2
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));小提琴。另请注意,$realData不存在的键$entities将被添加到结果中。

呼唤远方

您可以使用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);
打开App,查看更多内容
随时随地看视频慕课网APP