通过php键比较多维数组值 [英] Compare multidimensional array values by key in php

查看:50
本文介绍了通过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(
'价格'=>'$ 300',
'数量'=>'2件。',
'可用性'=>'有库存',
'制造商'=>' ')
);

我需要按每个键比较产品的值。为了突出显示比较表中价格,数量,可用性或制造商不同的行。



我尝试使用此函数来检查哪些值不同并返回一个临时数组:

  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 ++;
}

返回$ temp_array;
}

然后:



< pre class = lang-php prettyprint-override> foreach($ all_products作为$ products){
foreach($ products作为$ 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;'; ///突出显示样式
}
}
}
}

问题是当数组中的某些值为空时。像本例一样,制造商



也许有人有更好的解决方案?

解决方案


我需要按每个键比较乘积的值。要突出显示比较表中价格,数量,可用性或
制造商不同的行


如果您要突出显示所有产品,除非它们的价格,数量,可用性或制造商完全相同。



功能:

 函数productsIdentical(array& $ products):bool 
{
if(count($ products)< 2){
抛出新的\InvalidArgumentException(您应该传递至少2个产品进行比较);
}

$ compare =’;
foreach($ products作为$ product){
ksort($ product); //比较不敏感的键顺序
$ sha = sha1(json_encode($ product));
if(empty($ compare)){
$ compare = $ sha;
} elseif($ sha!== $ compare){
返回false;
}
}
返回true;
}

仅返回 true 如果所有产品的字段具有完全相同的键和值,否则将返回 false



,因此您可以使用它方式:

  $ identicalFlag = productsIdentical($ all_products); 
if($ identicalFlag === false){
echo产品不相同:。 PHP_EOL;

$ nonIdenticalProductsArr = array_keys($ all_products);
echo非相同的产品是:。 PHP_EOL;
print_r($ nonIdenticalProductsArr);

//对$ nonIdenticalProducts

}进行样式设置{{b $ b echo Products are same。 PHP_EOL;
}




输出:


相同产品:

 产品相同

对于非相同:

 产品不相同:
不相同的产品是:
数组

[0] => product_1
[1] => product_2
[2] => product_3

或者如果您想检测此数组中所有产品之间不相同的每个产品字段,请使用以下函数:

 函数getFieldsNonIdentical(array& $产品):数组
{
if(count($ products)< 2){
throw new \InvalidArgumentException(您应该传递至少2个产品进行比较);
}

$ compareArr = [];
$ keyDifferentArr = [];
foreach($ products作为$ 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不相同的字段:。 PHP_EOL;

print_r($ fieldsNonIdentical);

//进行样式

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

echo非相同的字段样式为:。 PHP_EOL;
print_r($ styleArr);
} else {
echo所有产品中的所有字段都相同。 。 PHP_EOL;
}




输出


表示相同:

 所有产品中的所有字段均相同。 

对于非相同:

 不相同的字段:
数组

[0] =>价格
[1] =>制造商

非相同字段的样式为:
数组

[price] => style = background-color:lightblue;
[manufacturer] => style = background-color:lightblue;


I have an array of the products as in the sample below. Products can be two, or three and more. In this example, three.

$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'=>'')
);

I need to compare values of the products by each key. To highlight rows in the compare table where price, quantity, availability, or manufacturer is different.

I have tried this function to check which values are different and return one temp array:

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;
}   

and then:

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    
            }
        }
    } 
}

Problem is when some value in array is empty. Like in this example, manufacturer.

Maybe someone has more light solution?

解决方案

I need compare values of the products by each key. To highlight rows in the compare table where price, quantity, availability, or manufacturer is different.

If you want to highlight all products unless all of them have exactly the same price, quantity, availability, or 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;
}

returns true only if all products' fields have exactly the same keys and value, otherwise it returns false

so you use it this way:

$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:

for identical products:

Products are identical

for non identical:

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

Or if you want to detect every product field that is not the same across all products in the array use this 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);
}

this way:

$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

for identical:

All fields in all products are the same.

for non identical:

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;"
)

这篇关于通过php键比较多维数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆