为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
小怪兽爱吃肉 2023-10-22 21:35:43
我有下面的数组,其中包括一组默认索引,它们必须出现在我的最终数组中:'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" => []  ]]正如您所看到的,如果将返回的数组与我期望的索引进行比较,会发现缺少一些内容:deliveredAttotals.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值?
查看完整描述

2 回答

?
手掌心

TA贡献1942条经验 获得超3个赞

您可以使用键和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将被添加到结果中。


查看完整回答
反对 回复 2023-10-22
?
呼唤远方

TA贡献1856条经验 获得超11个赞

您可以使用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);


查看完整回答
反对 回复 2023-10-22
  • 2 回答
  • 0 关注
  • 65 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信