使用 PHP 脚本从对象数组中的 JSON 对象数组中获取对象

问题描述 投票:0回答:1

两个 JSON 文件包含 JSON 对象,一个 JSON 文件包含对象数组中的对象数组。 文件orders.json:

{
    "orders": [
        {
            "address": null,
            "createdAt": "2023-09-13T12:17:32Z",
            "nmId": 1715161312, *ID of product's card
            "chrtId": 28173947  *ID of product's size
        },
        ...
        ]
}

文件card.json:

[
    {       
        "nmID": 1715161312,
        "vendorCode": "22SP-456P-nero",
        "sizes": [
            {
                "techSize": "2",
                "chrtID": 28173946,
                "price": 900
            },
            {
                "techSize": "3",
                "chrtID": 28173947,
                "price": 700
            }
          ]
    },...

我需要附加“techSize”、“price”、卡片文件中的信息以及“vendorCode”。我试图这样做:

// Iterate over the orders in new_orders_with_tags.json
foreach ($newOrdersData['orders'] as &$order) {
    // Find the corresponding card in cards.json based on chrtId
    $card = array_filter($cardsPlusData, function ($item) use ($order) {
        return $item['chrtID'] == $order['chrtID'];
    });

    // If a matching card is found, extract the required data
    if (!empty($card)) {
        $card = reset($card);
        $order['vendorCode'] = $card['vendorCode'];
        $order['techSize'] = $card['sizes'][0]['techSize'];
        $order['price'] = $card['sizes'][0]['price'];
    }
}

由于某种原因,我无法联系到 chrtId,也无法了解原因。有任何想法吗? 这可能是一种错误的做法。是不是应该先找到“产品卡片ID”,然后再找到对应的尺寸?

javascript php arrays json multidimensional-array
1个回答
0
投票

您需要更新 array_filter,如下所示:

$card = array_filter($cardsPlusData, function ($item) use ($order) {
        return $item['nmID'] == $order['nmID'];
    });

要获取特定的

techsize
,您需要为
card['size']
运行另一个过滤器:

$orderSize = array_filter($card['size'], function ($size) use ($order) {
        return $size['chartID'] == $order['chrtID'];
    });

现在在

$orderSize
内,您将得到如下所示的单个结果:

{
                "techSize": "2",
                "chrtID": 28173946,
                "price": 900
            },

你可以获得techSize

$orderSize =  $orderSize['techSize']; // check if not empty first
© www.soinside.com 2019 - 2024. All rights reserved.