简体   繁体   中英

How to get array key with less than values

I have 2 arrays:

$arr_1=array(200, 300, 200, 200);

$arr_2=array(
    1 => array(70, 90, 70, 20),
    2 => array(115, 150, 115, 35),
    3 => array(205, 250, 195, 55),
    4 => array(325, 420, 325, 95),
    5 => array(545, 700, 545, 155)
);

Now I need some way to get array keys for arrays in $arr_1 where all their values are less than all values from $arr_2 .

In the above example it must return key 1 AND key 2 from $arr_2 without using a foreach loop.

You can use array_filter to filter the elements (it preserves keys) and then pass the result to array_keys to receive an array of keys.

Also, your condition can be spelled this way: "return subarrays from $arr_2 where highest value is smaller than smallest value of $arr_1."

$arr_1=array(200, 300, 200, 200);

$arr_2=array(
    1 => array(70, 90, 70, 20),
    2 => array(115, 150, 115, 35),
    3 => array(205, 250, 195, 55),
    4 => array(325, 420, 325, 95),
    5 => array(545, 700, 545, 155)
);

$filtered = array_filter($arr_2, function($value) use ($arr_1) {
    return max($value) < min($arr_1);
});
$keys = array_keys($filtered);

var_dump($keys);

If you are only interested in comparing the subarrays against the lowest value in $arr_1 , then best practices dictates that you declare that value before entering the array_filter() . This will spare the function having to call min() on each iteration. ( Demo )

$arr_1=[200,300,200,200];
$arr_2=[
    1=>[70,90,70,20],
    2=>[115,150,115,35],
    3=>[205,250,195,55],
    4=>[325,420,325,95],
    5=>[545,700,545,155]
];

$limit=min($arr_1);  // cache this value, so that min() isn't called on each iteration in array_filter()
$qualifying_keys=array_keys(array_filter($arr_2,function($a)use($limit){return max($a)<$limit;}));
var_export($qualifying_keys);
/*
array(
    0=>1,
    1=>2,
)
*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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