亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

根據默認索引動態向數組添加空索引

根據默認索引動態向數組添加空索引

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 關注
  • 173 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號