将产品价格从一个二维数组映射并替换为另一个二维数组,然后按更新的价格排序

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

我正在尝试将 2 组数组与相同的键进行比较

product_sku

API 上的数组(JSON 响应)

$array1 = array (
    "products" => array(
        "category" => array(
            array(
                "product_sku" => "1",
                "product_type" => "Type",
                "customer_contact_name" => "Contact Name",
                "customer_telephone" => "0000 000 000",
                "customer_email" => "[email protected]",
                "customer_postcode" => "PostCode",
                "additional_info" => array(
                    "some information" => "some information"
                ),
                "full_price" => "50.00",
                "product_name" => "Product Name",
                "product_id" => "1",
                "customer_rating" => "0"
            ),
            array(
                "product_sku" => "2",
                "product_type" => "Type",
                "customer_contact_name" => "Contact Name",
                "customer_telephone" => "0000 000 000",
                "customer_email" => "[email protected]",
                "customer_postcode" => "PostCode",
                "additional_info" => array(
                    "some information" => "some information"
                ),
                "full_price" => "100.00",
                "product_name" => "Product Name",
                "product_id" => "2",
                "customer_rating" => "0"
            )
        )
    )
);

本地数据库数组(mysqli 查询)

$array2 = array (
    array(
        "product_sku" => "1",
        "product_type" => "Type",
        "contact_name" => "Contact Name",
        "phone" => "0000 000 000",
        "full_price" => "0.00",
        "product_name" => "Product Name",
        "product_id" => "1",
        "rating" => "0"
    ),
    array(
        "product_sku" => "3",
        "product_type" => "Type",
        "contact_name" => "Contact Name",
        "phone" => "0000 000 000",
        "full_price" => "80.00",
        "product_name" => "Product Name",
        "product_id" => "3",
        "rating" => "0"
    )
);

目标是

  1. 检查

    $array2
    $array1
    和仅当
    product_sku
    匹配(存在于
    $array1
    ),从
    full_price
    获取
    $array1
    并替换
    full_price
    中的

    $array2
  2. 如果

    product_id
    中的
    $array1
    $array2
    中不存在,请忽略那些产品。

  3. 使用

    sort
    功能对产品价格(从低到高)进行排序

我试过的是,部分工作但无法使用

sort
功能对产品价格(从低到高)进行排序,它显示 0.00
full_price
某些产品的价值

$apiarray = $array1["products"]["category"];

foreach ($array2 as $arr2) {
    foreach ($apiarray as $arr1) {
        if ($arr1['product_sku']==$arr2['product_sku']) {
            echo $arr2['product_sku']; // Product from $array2
            echo number_format($arr1['full_price'],2); // Price from $array1
        } else {
            echo $arr2['product_sku']; // Product from $array2
            echo number_format($arr2['full_price'],2); // Price from $array2
        }
    }
)

我需要帮助来确定我们的目标或为我指明正确的方向我怎样才能实现目标

php arrays sorting multidimensional-array mapping
3个回答
1
投票

你可以这样做:

//Make a temp associative array. This will make the product_sku as the key
//This is to make it easier to check if product_sku exist
$arrayTemp1 = array_column($array1['products']['category'], null, 'product_sku');

//Loop thru the array2.
//Check if the key exist on temp array. If it does, update the price
foreach( $array2 as &$value ) {
    if ( isset( $arrayTemp1[ $value['product_sku'] ] ) ) 
        $value['full_price'] = $arrayTemp1[ $value['product_sku'] ]['full_price'];
}

//Sort the $array2 using usort
usort( $array2, function($a, $b){
    return $a['full_price'] - $b['full_price'];
});

echo "<pre>";
print_r( $array2 );
echo "</pre>";

这将导致:

Array
(
    [0] => Array
        (
            [product_sku] => 1
            [product_type] => Type
            [contact_name] => Contact Name
            [phone] => 0000 000 000
            [full_price] => 50.00
            [product_name] => Product Name
            [product_id] => 1
            [rating] => 0
        )

    [1] => Array
        (
            [product_sku] => 3
            [product_type] => Type
            [contact_name] => Contact Name
            [phone] => 0000 000 000
            [full_price] => 80.00
            [product_name] => Product Name
            [product_id] => 3
            [rating] => 0
        )

)

1
投票

您不是在编辑

$array2
,而只是在循环中打印。你的第二步不是必需的,它来自你的嵌套
foreach
.


首先,您可以获得 SKU 列表:

$sku_list = array_column($array1['products']['category'], 'product_sku');

然后更新价格:

// Loop through the 2nd array
for ($i = 0; $i < count($array2); $i += 1) {
    if (in_array($array2[$i]['product_sku'], $sku_list)) {

        // Get the index of the 1st array item which SKU is matching, and update
        $index = array_search($array2[$i]['product_sku'], $sku_list);
        $array2[$i]['full_price'] = $array1['products']['category'][$index]['full_price'];
    }
}

然后使用

usort()
和PHP7的宇宙飞船运算符进行排序(如果PHP版本较低,则易于替换):

usort($array2, function($a, $b) { return $a['full_price'] <=> $b['full_price']; });

0
投票

如果用 PHP 完成,这道题需要 3 个基本任务。 (完整演示

  1. 根据

    product_sku
    值和
    full_price
    值创建查找数组。
    array_column()
    是构建关联数组最合适的函数。

    $skuFullPrices = array_column(
        $array1['products']['category'],
       'full_price',  // column to be values
       'product_sku'  // column to be keys
    );
    
  2. 将第一个数组中的

    full_price
    值映射到第二个数组中具有相应
    product_sku
    的行。

    $array2 = array_map(
        fn($row) =>
            array_replace(
                $row,
                ['full_price' => $skuFullPrices[$row['product_sku']] ?? $row['full_price']]
            ),
        $array2
    );
    

    $array2 = array_map(
        function($row) use ($skuFullPrices) {
             $row['full_price'] = $skuFullPrices[$row['product_sku']] ?? $row['full_price'];
             return $row;
        },
        $array2
    );
    
  3. 根据

    full_price
    值从第二个数组中按升序对更新后的数组进行排序。

    usort(
        $array2,
        fn($a, $b) => $a['full_price'] <=> $b['full_price']
    );
    

也就是说,现代 PHP 和现代 MYSQL 允许在 SQL 中完整而简洁地完成此任务。 JSON 编码您的 API 数据,将其作为参数传递到准备好的语句中作为 LEFT JOINed 派生表,然后合并 full_price 值并按全价排序。

代码:(PHPize.online Demo

$json = json_encode(
    /* $yourarray['products']['category'] */
);

$sql = <<<SQL
SELECT prod.product_sku,
       prod.product_type,
       prod.contact_name,
       prod.phone,
       COALESCE(api.full_price, prod.full_price) AS full_price,
       prod.product_name,
       prod.product_id,
       prod.rating
FROM products AS prod
LEFT JOIN JSON_TABLE(
         ?,
         '$[*]'
         COLUMNS (
                  product_sku INT PATH '$.product_sku',
                  full_price VARCHAR(100) PATH '$.full_price'
         )
     ) AS api ON prod.product_sku = api.product_sku
ORDER BY full_price
SQL;

var_export(
     $mysqli->execute_query($sql, [$json])->fetch_all(MYSQLI_ASSOC)
);
© www.soinside.com 2019 - 2024. All rights reserved.