繁体   English   中英

PHP 从多维数组中搜索值

[英]PHP search values from multidimensional array

我有两个 arrays 如下:

$price = [
    34 => 65.00,
    35 => 95.00,
    36 => 125.00,
];

$dbPrices = [
    36 => [
        'sales_price' => 125.00,
        'our_price' => 0.00
    ],
    35 => [
        'sales_price' => 98.00,
        'our_price' => 0.00
    ],
    34 => [
        'sales_price' => 70.00,
        'our_price' => 65.00
   ]
];

我真正想知道$price数组中的值是否存在于第二个数组中。 在这种情况下,可以检查sales_priceour_price包含$price数组中的值。

如果$price数组中的那些值在第二个数组中找不到,则必须从这些值创建一个新数组。

因此,新数组应如下所示:

$newPrices = [35 => 95]

这就是我尝试的方式。 $dbPrices 是我的第二个数组:

$discountItems = [];
$discountItems = array_intersect_key($price, $dbPrices);

$filter = function($v,$k) use($dbPrices){
return array_values($dbPrices[$k]) != $v;
};

$newPrices = array_filter($discountItems, $filter, ARRAY_FILTER_USE_BOTH );

它不能以这种方式工作。 有人可以帮我解决这个问题吗?

您的过滤器逻辑当前正在将一个数组与一个数字进行比较。 我相信您正在寻找的解决方案可能与使用in_array一样简单:

<?php

$price = [
    34 => 65.00,
    35 => 95.00,
    36 => 125.00,
];

$dbPrices = [
    36 => [
        'sales_price' => 125.00,
        'our_price' => 0.00
    ],
    35 => [
        'sales_price' => 98.00,
        'our_price' => 0.00
    ],
    34 => [
        'sales_price' => 70.00,
        'our_price' => 65.00
    ]
];


$discountItems = [];
$discountItems = array_intersect_key($price, $dbPrices);

$filter = function($v,$k) use($dbPrices){
    return !in_array($v, array_values($dbPrices[$k]));
};

$newPrices = array_filter($discountItems, $filter, ARRAY_FILTER_USE_BOTH );

print_r($newPrices);

output:

数组([35] => 95)

您可以使用 foreach 并使用它的键将 $price 数组与 $dbPrices 一起使用。 如果 sales_price 或 our_price 匹配,则继续循环,否则将不匹配的 $price 数组值存储在 $dbPrices 数组中。 试试下面的代码。

 <?php
        $price = [
            34 => 65.00,
            35 => 95.00,
            36 => 125.00,
        ];
        
        $dbPrices = [
            '36' => [
                'sales_price' => 125.00,
                'our_price' => 0.00
            ],
            '35' => [
                'sales_price' => 98.00,
                'our_price' => 0.00
            ],
            '34' => [
                'sales_price' => 70.00,
                'our_price' => 65.00
           ]
        ];
        
        $newPrices = [];
        foreach($dbPrices as $key => $value ) {
            if ($price[$key] == $value['sales_price'] || $price[$key] == $value['our_price']) {
                continue;   
            }else{
                $newPrices[$key] = $price[$key];
            }
        }
    
    print_r($newPrices);
    ?> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM