簡體   English   中英

在 php 中按鍵比較多維數組值

[英]Compare multidimensional array values by key in php

我有一系列產品,如下面的示例所示。 產品可以是兩個,也可以是三個甚至更多 在這個例子中,三個。

$all_products = array(
    'product_1'       =>array(
        'price'       =>'$100',
        'quantity'    =>'2pcs.',
        'availability'=>'In Stock',
        'manufacturer'=>'Apple'),
    'product_2'       =>array(
        'price'       =>'$200',
        'quantity'    =>'2pcs.',
        'availability'=>'In Stock',
        'manufacturer'=>''),
    'product_3'       =>array(
        'price'       =>'$300',
        'quantity'    =>'2pcs.',
        'availability'=>'In Stock',
        'manufacturer'=>'')
);

我需要按每個鍵比較產品的值。 在比較表中突出顯示價格、數量、可用性或制造商不同的行。

我試過這個 function 來檢查哪些值不同並返回一個臨時數組:

function compare_array($array, $key) {
    $temp_array = array();
    $i = 0;
    $key_array = array();

    foreach($array as $val) {
        if (isset($val[$key])) {
            if (!in_array($val[$key], $key_array)) {
                $key_array[$i] = $val[$key];
                $temp_array[$i] = $val;
            } 
        }
        $i++;
    }

    return $temp_array;
}   

接着:

foreach ($all_products as $products) {
    foreach ($products as $product_key => $val) {
        foreach ($this->compare_array($all_products, $product_key) as $temp_value) { 
            if ($val != $temp_value) {
                $style[$product_key] = 'style="background-color: lightblue;"';//style for highlight    
            }
        }
    } 
}

問題是當數組中的某個值為空時。 就像在這個例子中, manufacturer

也許有人有更輕的解決方案?

我需要按每個鍵比較產品的值。 在比較表中突出顯示價格、數量、可用性或制造商不同的行。

如果您想突出顯示所有產品,除非它們的價格、數量、可用性或制造商完全相同。

function:

function productsIdentical(array &$products) : bool
{
    if (count($products) < 2) {
        throw new \InvalidArgumentException("You should pass at least 2 products to compare");
    }

    $compare = '';
    foreach ($products as $product) {
        ksort($product); //to make comparison of key order insensitive
        $sha = sha1(json_encode($product));
        if (empty($compare)) {
            $compare = $sha;
        } elseif ($sha !== $compare) {
            return false;
        }
    }
    return true;
}

僅當所有產品的字段具有完全相同的鍵和值時才返回true ,否則返回false

所以你這樣使用它:

$identicalFlag = productsIdentical($all_products);
if ($identicalFlag === false) {
    echo "Products are not identical:" . PHP_EOL;

    $nonIdenticalProductsArr = array_keys($all_products);
    echo "Non identical products are:" . PHP_EOL;
    print_r($nonIdenticalProductsArr);

    //do your styling  on $nonIdenticalProducts

} else {
    echo "Products are identical" . PHP_EOL;
}

Output:

對於相同的產品:

Products are identical

對於不相同的:

Products are not identical:
Non identical products are:
Array
(
    [0] => product_1
    [1] => product_2
    [2] => product_3
)

或者,如果您想檢測陣列中所有產品中不同的每個產品字段,請使用此 function:

function getFieldsNonIdentical(array &$products) : array
{
    if (count($products) < 2) {
        throw new \InvalidArgumentException("You should pass at least 2 products to compare");
    }

    $compareArr = [];
    $keyDifferentArr = [];
    foreach ($products as $product) {
        foreach($product as $key => $val) {
            if (!key_exists($key, $compareArr)) {
                $compareArr[$key] = $val;
            } elseif ($compareArr[$key] !== $val) {
                $keyDifferentArr[$key] = true;
            }
        }
    }
    return array_keys($keyDifferentArr);
}

這邊走:

$fieldsNonIdentical = getFieldsNonIdentical($all_products);

if (!empty($fieldsNonIdentical)) {
    echo "Fields that are non identical:" . PHP_EOL;

    print_r($fieldsNonIdentical);

    //do your styling

    $nonIdenticalStyle = 'style="background-color: lightblue;"';
    $styleArr = [];
    foreach ($fieldsNonIdentical as $key => $value) {
        $styleArr[$value] = $nonIdenticalStyle;
    }

    echo "Non Identical fields styling is:" . PHP_EOL;
    print_r($styleArr);
} else {
    echo "All fields in all products are the same." . PHP_EOL;
}

Output

對於相同的:

All fields in all products are the same.

對於不相同的:

Fields that are non identical:
Array
(
    [0] => price
    [1] => manufacturer
)
Non Identical fields styling is:
Array
(
    [price] => style="background-color: lightblue;"
    [manufacturer] => style="background-color: lightblue;"
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM